Linq to XML, how to acess an element in C#?

拜拜、爱过 提交于 2019-12-12 03:05:22

问题


Here is my XML I need to parse:

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

To access the <text> element I use this code:

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

How can I access <photo:mtime>?


回答1:


The element mtime is in the namespace that is mapped to photo. You can access it as follows:

var doc = XDocument.Parse(xml.Text);
XNamespace ns = "your nanespace URI goes here"
doc.Descendants(ns + "mtime").FirstOrDefault().Value;

However, without a namepsace mapping, your XML document is invalid. I would expect it to look like this:

 <root xmlns:photo="your nanespace URI goes here">
         <photo>/filesphoto.jpg</photo>
         <photo:mtime>12</photo:mtime>
         <text>some text</text>
 </root>



回答2:


it is an illegal format of xml my friend you cannot have a colon




回答3:


The answer is here How to Load and access data with Linq to XML from XML with namespaces Thanks for jmh_gr Parsing xml fragments with namespaces into an XElement:

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)));
}

Using your exact input:

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);

Prints:

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


来源:https://stackoverflow.com/questions/8739195/linq-to-xml-how-to-acess-an-element-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!