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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With