【问题标题】:XPathEvaluate does not evaluate a valid XPathXPathEvaluate 不评估有效的 XPath
【发布时间】:2013-06-09 10:58:34
【问题描述】:

示例 xml:

<pr:InquiredPersonCode xmlns:pr="http://some/XMLSchemas/PR/v1-0" xmlns:epcs="http://some/XMLSchemas/EP/v1-0">
  <pr:PersonCode>111</pr:PersonCode>
  <pr:EServiceInstance>
      <epcs:TransactionID>Tran-1</epcs:TransactionID>
  </pr:EServiceInstance>
</pr:InquiredPersonCode>

以及有效且格式良好的 XPath:

/*[local-name()='InquiredPersonCode' and namespace-uri()='http://some/XMLSchemas/PR/v1-0']/*[local-name()='EServiceInstance' and namespace-uri()='http://some/XMLSchemas/PR/v1-0']/*[local-name()='TransactionID' and namespace-uri()='http://some/XMLSchemas/EP/v1-0']

然后在代码中:

var values = message.XPathEvaluate(xPath);

结果为空。

【问题讨论】:

    标签: .net xml xpath xml-parsing


    【解决方案1】:

    Brian,您使用的是哪个 XPath API?当我对您的文件使用 System.Xml SelectNodes 方法或 LINQ 扩展方法 XPathEvaluate 时,它会找到一个元素。这是一个示例:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;
    
    namespace ConsoleApplication45
    {
        class Program
        {
            static void Main(string[] args)
            {
                string path = "/*[local-name()='InquiredPersonCode' and namespace-uri()='http://some/XMLSchemas/PR/v1-0']/*[local-name()='EServiceInstance' and namespace-uri()='http://some/XMLSchemas/PR/v1-0']/*[local-name()='TransactionID' and namespace-uri()='http://some/XMLSchemas/EP/v1-0']";
    
                XmlDocument doc = new XmlDocument();
                doc.Load("../../XMLFile1.xml");
    
                foreach (XmlElement el in doc.SelectNodes(path))
                {
                    Console.WriteLine("Element named \"{0}\" has contents \"{1}\".", el.Name, el.InnerText);
                }
    
                Console.WriteLine();
    
                XDocument xDoc = XDocument.Load("../../XMLFile1.xml");
    
                foreach (XElement el in (IEnumerable)xDoc.XPathEvaluate(path))
                {
                    Console.WriteLine("Element named \"{0}\" has contents \"{1}\".", el.Name.LocalName, el.Value);
                }
            }
        }
    }
    

    输出是

    名为“epcs:TransactionID”的元素的内容为“Tran-1”。

    名为“TransactionID”的元素的内容为“Tran-1”。

    我不会使用XPathEvaluate 来选择元素,XPathSelectElements 更容易使用。我同意使用命名空间的 cmets,你可以简单地做

       XDocument xDoc = XDocument.Load("../../XMLFile1.xml");
    
    
        foreach (XElement id in xDoc.XPathSelectElements("pr:InquiredPersonCode/pr:EServiceInstance/epcs:TransactionID", xDoc.Root.CreateNavigator()))
        {
            Console.WriteLine("Found id {0}.", id.Value);
        }
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2010-11-03
      • 1970-01-01
      • 2018-03-31
      • 2013-07-13
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      相关资源
      最近更新 更多