简体   繁体   中英

How to access XML Node with Special Character from XmlDocument using SelectNodes in c#

I have following XML:

<Doc>
 <Entries>
  <Entry>
    <RowA>Test</RowA>
    <RowB>Hello</RowB>
    <Row:C>Try to Access me </Row:C>
  </Entry>

  <Entry>
    <RowA>Try Again</RowA>
    <RowB>Hello2</RowB>
    <Row:C>Try to Access me again </Row:C>
  </Entry>

  </Entries>
</Doc>

Following my code, everything is working fine except Row:C

XmlNodeList xmlNodeList = xmlFile.SelectNodes("Doc/Entries/Entry");

foreach (XmlNode xmlNode in xmlNodeList)
{
 String _Ok = xmlNode.SelectSingleNode("RowA").InnerText;
 String _Error = xmlNode.SelectSingleNode("Row:C").InnerText;  // ERROR
}

Following the error:

Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

Thank you in advance for your time.

You xml contains namespace so you need to use XmlNamespaceManager to for resolving namespace for prefixes in the XPath expression.

class Program
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();

        doc.Load(@"Path to your xml file");

        XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
        ns.AddNamespace("Row", "http://www.namespace.com/");    // <= Replace your namespace here that start with "xmlns:Row="http://www.namespace.com/"" in root of document
        XmlNodeList nodes = doc.SelectNodes("//Doc//Entries//Entry//*", ns);

        foreach (XmlNode node in nodes)
        {
            Console.WriteLine(node.InnerText);
        }

        Console.ReadLine();
    }
}

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM