【问题标题】:How to access XML Node with Special Character from XmlDocument using SelectNodes in c#如何使用 C# 中的 SelectNodes 从 XmlDocument 访问具有特殊字符的 XML 节点
【发布时间】:2018-12-12 09:51:31
【问题描述】:

我有以下 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>

按照我的代码,一切正常,除了 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
}

以下错误:

需要命名空间管理器或 XsltContext。此查询具有前缀、变量或用户定义的函数。

提前感谢您的宝贵时间。

【问题讨论】:

  • 能否请您出示完整的 xml?
  • 我想你忘了在下面查看我的答案。让我知道它是否对您有帮助?

标签: c# xmldocument


【解决方案1】:

您的 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();
    }
}

输出:

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 2012-04-22
    • 2021-10-27
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多