示例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);
结果为空。
答案 0 :(得分:2)
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
更容易使用。我同意使用命名空间的注释,你可以简单地做
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);
}