Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq-to-XML get elements with namespace

i am using linq-to-xml to search elements.

 var doc = XDocument.Load(reader);
                    var ns = doc.Root.Attribute("xmlns").Value;
                    var result = (from u in doc.Descendants(XName.Get("MyElement", ns))

i need to get rid of using XName.Get whenever i try to find an element in xml. how can i set a default namespace to XDocument so that it will not bother when searching.

Regards.

like image 741
Shoaib Shaikh Avatar asked Apr 24 '12 12:04

Shoaib Shaikh


3 Answers

Here is one way of ignoring default namespaces, if you really want to do that:

        XDocument doc;
        using (XmlTextReader xr = new XmlTextReader("input.xml"))
        {
            xr.Namespaces = false;
            doc = XDocument.Load(xr);
        }
        foreach (XElement bar in doc.Descendants("bar"))

But I would suggest to accept the existence and importance of namespaces in XML and use the XName and XNamespace objects LINQ to XML provides to work with them.

like image 167
Martin Honnen Avatar answered Sep 30 '22 22:09

Martin Honnen


i need to get rid of using XName.Get whenever i try to find an element in xml. how can i set a default namespace to XDocument so that it will not bother when searching.

You can't - but there are two other options:

  • Use the +(XNamespace, string) operator:

    doc.Descendants(ns + "MyElement")
    
  • Just create the XName values once, then refer to them in your query, e.g.

    XName myElementName = ns + "MyElement";
    ...
    doc.Descendants(myElementName);
    

Ideally, you wouldn't create the namespace dynamically anyway - don't you know the namespace you should be looking in? If you do, you can create private static readonly fields with the appropriate XName values.

like image 31
Jon Skeet Avatar answered Sep 30 '22 22:09

Jon Skeet


Can't you do:

doc = XDocument.Load(reader);
var ns = doc.Root.Attribute("xmlns").Value;
var result = from u in doc.Descendants.Elements(ns+"MyElement").Select(c=>c.Value);
like image 42
Habib Avatar answered Sep 30 '22 22:09

Habib