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.
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it worked now. But I do not need to add the nmspc.AddNamespace("addData", "example.com/file2.xsd"); line, but instead nsmgr.AddNamespace("_colored", "example.com/colored.xsd"); Please, fix it in your answer, so that we do not mislead someone else :)
Thank you for finding the bug. I did not test the code when I first wrote the answer, now it's tested and working.
1

LINQ to Xml can make things easier:

 XDocument doc = XDocument.Load(filePath);
 var value = doc.Descendants("_Field1").First().Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.