XML : C# XDocument.XPathEvaluate - Handling namespaces at runtime

I'm trying to display any given xml file in a custom GUI and when the user selects an element or attribute the xpath of that object should be displayed. All the GUI stuff is done, but I am having some issues handling all the namespace stuff at runtime. This is what I have:

  XDocument document = XDocument.Load("somefile.xml");  XPathNavigator navigator = document.CreateNavigator();  navigator.MoveToFollowing(XPathNodeType.Element);  IDictionary<string, string> namespaces = navigator.GetNamespacesInScope(XmlNamespaceScope.All);  XmlReader reader = document.CreateReader();  XmlNamespaceManager manager = new XmlNamespaceManager(reader.NameTable);    foreach (KeyValuePair<string, string> ns in namespaces)      manager.AddNamespace(ns.Key, ns.Value);    

Using XDocument.XPathEvaluate should give me the xpath, but for the given xml it returns 0 matches no matter what xpath i try:

  <?xml version="1.0" encoding="UTF-8"?>  <Invoice xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2">      <cbc:UBLVersionID>2.1</cbc:UBLVersionID>      <cbc:IssueDate>2015-06-30</cbc:IssueDate>      ...  </Invoice>    

1) Why is my code unable to produce an xpath for the above xml?

2) Can anyone point me in the right direction on handling "any" given namespace at runtime?

No comments:

Post a Comment