infoexpert.it
infoexpert.it

Reputation: 345

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

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

Answers (3)

infoexpert.it
infoexpert.it

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

Hussein Zawawi
Hussein Zawawi

Reputation: 2937

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

Upvotes: 2

ColinE
ColinE

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

Related Questions