0

I'm having troubles using Xml on my C# program.

the xml http://pastebin.com/Ufxaght6 (from sandbox)

I'm trying to get any info on the XML, I succeed using recursive loop on nodes, but I want to use something more efficient.

I'm trying this :

XmlDocument document = new XmlDocument();
        document.LoadXml(response);

        XmlNode node = document.SelectSingleNode("/getnewsalesresult/request/user");
        if (node != null)
            Logger.WriteLine(node.InnerText);
        else
            Logger.WriteLine("fail");

This gives always a null. I think the problem comes from the 'getnewsalesresult' (Wildcard maybe ?).

From the XML :

  <getnewsalesresult xmlns="http://www.sandbox.priceminister.com/res/schema/getnewsales" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.sandbox.priceminister.com/res/schema/getnewsales http://www.sandbox.priceminister.com/res/schema/getnewsales/getnewsales.2014-02-11.xsd">

Any idea ?

Thanks in advance.

  • I suspect it's a namespace issue. Try http://stackoverflow.com/questions/1145659/ignore-namespaces-in-linq-to-xml – AaronLS Aug 28 '14 at 14:59
  • I don't want to be spoon feed, but I have no clue how to start for this :) – Renaud G Aug 28 '14 at 15:04
  • SelectSingleNode takes xpath, first start with testing just the first level: `document.SelectSingleNode("/getnewsalesresult");` if that doesn't return anything try `document.SelectSingleNode("/[local-name()='getnewsalesresult']");` or `document.SelectSingleNode("/*[local-name()='getnewsalesresult']");` – AaronLS Aug 28 '14 at 15:12
  • From there add the next `/` level and try the variations, the local-name is basically a way to ignore namespaces. There is another approach where you declare all the namespaces that are in the document but it is tedious and not useful assuming your document has no name conflicts. – AaronLS Aug 28 '14 at 15:14

1 Answers1

0

Your XML has default namespace (xmlns="..."). Default namespace has a different nature. The element where the default namespace declared and all of it's descendant without prefix and without different namespace declaration considered in the same default namespace.

The easiest way to get element in namespace is just to ignore the namespace (as also suggested in comment to this question) :

string xpath = "/*[local-name()='getnewsalesresult']/*[local-name()='request']/*[local-name()='user']";
XmlNode node = document.SelectSingleNode(xpath);

A more proper way is to register a prefix that mapped to the default namespace URI, then use that prefix in your XPath :

XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("d", "http://www.sandbox.priceminister.com/res/schema/getnewsales");
XmlNode node = 
        document.SelectSingleNode("/d:getnewsalesresult/d:request/d:user", ns);

don't miss to pass XmlNamespaceManager object as 2nd parameter of SelectSingleNode().

har07
  • 88,338
  • 12
  • 84
  • 137