2012-01-05 2 views
-1

여기 이전 질문에서 문제를 해결하는 방법을 이해하지 못했습니다.네임 스페이스가있는 XML에서 Linq을 사용하여 XML에 데이터를 액세스하는 방법

var doc = XDocument.Parse(xml.Text); 
doc.Descendants("text").FirstOrDefault().Value; 

가 어떻게 액세스 할 수 있습니다

<root> 
     <photo>/filesphoto.jpg</photo> 
     <photo:mtime>12</photo:mtime> 
     <text>some text</text> 
</root> 

이 코드를 사용하는 요소에 액세스하려면 여기 Linq to XML, how to acess an element in C#? 내가 구문 분석 할 필요가 내 XML인가? 나는 시도했다 http://aspnetgotyou.blogspot.com/2010/06/xdocument-or-xelement-with-xmlnamespace.html, 그러나 그것은 무시된다 <photo:mtime>와 나는 그것을 접근 할 필요가있다. 코드를 작성하십시오.

+3

xml이면 Linq와 XML을 함께 구문 분석 할 수 없습니다. XML을 수정해야하며 이전 질문에 대한 대답도 참조하십시오. – BrokenGlass

+0

XML은 정확하지 않으므로 구문 분석 할 수 없습니다. 괜찮 으면,이 XML 파일을 VS로 열고'photo : mtime>'을'photoMtime>'으로 바꾸라고 제안 할 것입니다. –

답변

0

@BrokenGlass의 설명과는 달리 XML은 유효하지 않습니다. 실제로 네임 스페이스로드를위한 질문에서 제공 한 링크의 기술은 정상적으로 작동합니다. 어쩌면 당신은 자신의 필요에 따라 예제를 바꾸지 않았을 것입니다.

string xml = 
@"<root> 
    <photo>/filesphoto.jpg</photo> 
    <photo:mtime>12</photo:mtime> 
    <text>some text</text> 
</root>"; 
XElement x = parseWithNamespaces(xml, new string[] { "photo" }); 
foreach (XElement e in x.Elements()) { 
    Console.WriteLine("{0} = {1}", e.Name, e.Value); 
} 
Console.WriteLine(x.Element("{photo}mtime").Value); 

인쇄 :

photo = /filesphoto.jpg 
{photo}mtime = 12 
text = some text 
12 
+0

왜 메소드를 적용한 후에 다른 xml 결과를 얻을 수 있습니까? 1'<{photo} mtime> 12 mtime>' 2' 12' –

0

이 시도 : 정확한 입력을 사용

public static XElement parseWithNamespaces(String xml, String[] namespaces) { 
    XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(new NameTable()); 
    foreach (String ns in namespaces) { nameSpaceManager.AddNamespace(ns, ns); } 
    return XElement.Load(new XmlTextReader(xml, XmlNodeType.Element, 
     new XmlParserContext(null, nameSpaceManager, null, XmlSpace.None))); 
} 

: 여기 XElement를에 네임 스페이스와 XML 조각 을 구문 분석을위한 컴팩트 일반화이다 (당신의 XML이 약간 변경됨 참조)

string xml = "<root><photo>/filesphoto.jpg</photo><photoMtime>12</photoMtime><text>some text</text></root>"; 
var doc = XDocument.Parse(xml); 
string value = doc.Descendants("text").FirstOrDefault().Value; 
MessageBox.Show(value); 
관련 문제