How to use XPath with XDocument?

If you have XDocument it is easier to use LINQ-to-XML.

Up vote 6 down vote favorite 1 share g+ share fb share tw.

There is a similar question, but seems that solution didn't work out in my case Wierdness with XDocument, XPath and namespaces Here is the XML I am working with Demo Report Unit Test And below is the code that I thought it should be working but it didnt... XDocument xdoc = XDocument. Load(@"C:\SampleXML. Xml"); XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); xnm.

AddNamespace(String. Empty, "http://demo.com/2011/demo-schema"); Console. WriteLine(xdoc.

XPathSelectElement("/Report/ReportInfo/Name", xnm) == null); Anyone has any idea? Thanks. C# .net xml xpath xdocument link|improve this question edited Jun 4 '11 at 7:52Alex Aza16.5k52043 asked Jun 2 '11 at 2:40shrimpy1,16821237 77% accept rate.

If you have XDocument it is easier to use LINQ-to-XML: var document = XDocument. Load(fileName); var name = document. Descendants(XName.

Get("Name", @"demo.com/2011/demo-schema")).First(). Value; If you are sure that XPath is the only solution you need: var document = XDocument. Load("fileName"); // Added missing endquote.

It won't submit unless I type more. Var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager. AddNamespace("emtpy", "demo.com/2011/demo-schema"); var name = document.

XPathSelectElement("/emtpy:Report/emtpy:ReportInfo/emtpy:Name", namespaceManager).Value.

1 There was a missing endquote in there throwing off the syntax coloring. I added the quote, but it wouldn't let me submit without adding more, so I included the comment. Now it won't let me remove the extra comment.

Not sure how to fix that, sorry for the extraneous comment. – AaronM Jan 27 at 0:52.

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this: XDocument xdoc = XDocument. Load(@"C:\SampleXML.

Xml"); XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); xnm. AddNamespace("x", "http://demo.com/2011/demo-schema"); Console. WriteLine(xdoc.

XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null).

1 Your answer implies that XPath 2.0, in contrast of XPath 1.0 "*has" an idea" of a default namespace. I am not aware of such new XPath feature (we are talking XPath here, not XSLT or XQuery). Therefore, could you, please, explicitly mention in your answer what you are implying?

– Dimitre Novatchev Jun 2 '11 at 12:04.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions


Thank You!
send