1

IDE: VS 2010, winforms,

I have a xml string

string  xmlstr = "<string xmlns="http://example.com/proj1">True|Success</string>";    

I am trying to select the <string> node to get its InnerText for subsequent parsing:

True|Success  

using below code:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlstr);          
string message = xdoc.SelectSingleNode("string").InnerText;  //Here getting null Execption error.  

can you tell me how to select this message from xml?

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
yogeshkmrsoni
  • 315
  • 7
  • 21

1 Answers1

4

You need to add a XmlNamespaceManager to be able to select the node:

XmlNode.SelectSingleNode Method (String, XmlNamespaceManager)

string xmlstr = "<string xmlns=\"http://example.com/proj1\">True|Success</string>";    
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlstr);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("ab", "http://example.com/proj1");

XmlNode stringNode = xdoc.SelectSingleNode("//ab:string", nsmgr);
string message = stringNode.InnerText;

Besides your xml string is invalid in the example because it contains double quotes inside that are not escaped.

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
  • @Tomalak I've fixed the example. It wouldn't work (and it didn't) anyway with the suggested `XPath` because the node contains a namespace and a `XmlNamespaceManager` was necessary. – t3chb0t Dec 31 '14 at 08:50
  • ...an now it exactly matches the duplicate I've linked to. ;) – Tomalak Dec 31 '14 at 08:51
  • 1
    @Tomalak oh, sorry, I didn't mean to copy it. I actaully didn't realize that a namespace was used in the other question ;-] and solved it by myself... now I'm pround of me ;-] and I will feel ashamed that I missed this information in the duplicate hehe. – t3chb0t Dec 31 '14 at 08:55
  • Prefect explanation, thanks @t3chb0t – yogeshkmrsoni Dec 31 '14 at 09:22