Pregunta

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.
¿Fue útil?

Solución

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

Otros consejos

LINQ to Xml can make things easier:

 XDocument doc = XDocument.Load(filePath);
 var value = doc.Descendants("_Field1").First().Value;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top