简体   繁体   English

如何在C#中使用SelectNodes从XmlDocument访问具有特殊字符的XML节点

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

I have following XML: 我有以下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 按照我的代码,除了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. 需要名称空间管理器或XsltContext。 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. xml包含名称空间,因此您需要使用XmlNamespaceManager来解析XPath表达式中前缀的名称空间。

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: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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