查找名称中带有句点的元素
本文关键字:句点 元素 查找 | 更新日期: 2023-09-27 18:30:56
我有以下XML:
<T24.MESSAGE>
<TRANSACTION.TYPE>CHEQUE.ON.THEM.AUTH</TRANSACTION.TYPE>
<TRANSACTION.ID>FT14273PKQ14</TRANSACTION.ID>
</T24.MESSAGE>
我正在尝试使用 xpath 查询/TRANSACTION.TYPE
查找 TRANSACTION.TYPE
元素。但是,这不返回任何内容,我认为这是因为元素的名称中有一个句点。
有没有办法逃脱这个时期?尽管根据MS参考,但不需要。http://msdn.microsoft.com/en-us/library/ms256199%28v=vs.110%29.aspx
编辑:我也尝试过/T24.MESSAGE/TRANSACTION.TYPE
,只是TRANSACTION.TYPE
,都没有工作。
我用来读取它的代码:
byte[] xmlBytes = Encoding.UTF8.GetBytes(strXML);
using (MemoryStream xmlStream = new MemoryStream(xmlBytes))
{
XPathDocument doc = new XPathDocument(XmlReader.Create(xmlStream, xmlReaderSettings));
var navigator = doc.CreateNavigator();
var node = navigator.SelectSingleNode("/TRANSACTION.TYPE"); //null
//...
}
由于您使用的是命名空间,因此您可以尝试在代码中使用与命名空间无关的形式。它看起来像这样
var node = navigator.SelectSingleNode("//*[local-name()='TRANSACTION.TYPE']");
问题出在您的命名空间上。您需要创建一个XmlNamespaceManager
并将其传递给您的SelectSingleNode
呼叫。
在下面,我创建了一个urn:test
命名空间:
string strXML = @"<?xml version='1.0'?>
<T24.MESSAGE xmlns=""urn:Test"">
<TRANSACTION.TYPE>CHEQUE.ON.THEM.AUTH</TRANSACTION.TYPE>
<TRANSACTION.ID>FT14273PKQ14</TRANSACTION.ID>
</T24.MESSAGE>";
byte[] xmlBytes = Encoding.UTF8.GetBytes(strXML);
using (MemoryStream xmlStream = new MemoryStream(xmlBytes))
{
XPathDocument doc = new XPathDocument(XmlReader.Create(xmlStream));
var navigator = doc.CreateNavigator();
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(navigator.NameTable);
//Add the namespaces used. In this instance I'm setting a prefix of "t"
xmlnsManager.AddNamespace("t", "urn:Test");
//pass the XmlNamespaceManager to the call to SelectSingleNode
//the XPath also includes the root element
var node = navigator.SelectSingleNode("//t:T24.MESSAGE/t:TRANSACTION.TYPE", xmlnsManager);
Console.WriteLine(node.Name);
}
此代码正确输出
交易。类型
这
当然有效
string yourXMLString = @"<T24.MESSAGE>
<TRANSACTION.TYPE>CHEQUE.ON.THEM.AUTH</TRANSACTION.TYPE>
<TRANSACTION.ID>FT14273PKQ14</TRANSACTION.ID>
</T24.MESSAGE>";
XDocument xDoc = XDocument.Parse(yourXMLString);
var res = xDoc.Descendants("T24.MESSAGE")
.Elements("TRANSACTION.TYPE");
结果:<TRANSACTION.TYPE>CHEQUE.ON.THEM.AUTH</TRANSACTION.TYPE>