0

I have the following XML

<?xml version="1.0" encoding="UTF-8"?>
<form:Documents xmlns:form="http://www.example.com/file.xsd" xmlns:addData="http://www.example.com/file2.xsd">
    <_colored:_colored addData:DocumentState="Correct" xmlns:_colored="http://www.example.com/colored.xsd">
        <_colored>
            <_Field1>PB8996MT</_Field1>
        </_colored>
    </_colored:_colored>
</form:Documents>

I try to get the inner text of the _Field1 tag by writing the following C# code:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(filePath);

string fieldValue = xmlDocument.SelectSingleNode("/form:Documents/_colored:_colored/_colored/_Field1").InnerText;

And when I run the application I get the following exception:

Unhandled Exception: System.Xml.XPath.XPathException: Namespace Manager or XsltContext needed. 
This query has a prefix, variable, or user-defined function.
Andreas
  • 5,251
  • 30
  • 43
Yulian
  • 6,262
  • 10
  • 65
  • 92
  • possible duplicate of [How to Select XML Nodes with XML Namespaces from an XmlDocument?](http://stackoverflow.com/questions/4633127/how-to-select-xml-nodes-with-xml-namespaces-from-an-xmldocument) – Andreas May 09 '14 at 12:25

2 Answers2

1

You should declare the namespace prefix using an XmlNamespaceManager before you can use it in XPath expressions.

XmlDocument doc = new XmlDocument ();
doc.Load("/Users/buttercup/Projects/23564466/kram.xml");

XmlNamespaceManager nmspc = new XmlNamespaceManager(doc.NameTable);
nmspc.AddNamespace("form", "http://www.example.com/file.xsd");
nmspc.AddNamespace("addData", "http://www.example.com/file2.xsd");
nmspc.AddNamespace("_colored", "http://www.example.com/colored.xsd");

string fieldValue = doc.SelectSingleNode("/form:Documents/_colored:_colored/_colored/_Field1", nmspc).InnerText;

http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.aspx

Andreas
  • 5,251
  • 30
  • 43
  • Thank you, it worked now. But I do not need to add the nmspc.AddNamespace("addData", "http://www.example.com/file2.xsd"); line, but instead nsmgr.AddNamespace("_colored", "http://www.example.com/colored.xsd"); Please, fix it in your answer, so that we do not mislead someone else :) – Yulian May 09 '14 at 12:36
  • Thank you for finding the bug. I did not test the code when I first wrote the answer, now it's tested and working. – Andreas May 09 '14 at 12:57
1

LINQ to Xml can make things easier:

 XDocument doc = XDocument.Load(filePath);
 var value = doc.Descendants("_Field1").First().Value;
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112