Reputation: 345
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>
?
Upvotes: 0
Views: 117
Reputation: 345
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
Upvotes: 0
Reputation: 2937
it is an illegal format of xml my friend you cannot have a colon
Upvotes: 2
Reputation: 70160
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>
Upvotes: 2