当 Xml 元素以命名空间为前缀时,如何查找它?



我有一个Xml文件,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ea:Stories ea:WWVersion="2.0" xmlns:aic="http://ns.adobe.com/AdobeInCopy/2.0" xmlns:ea="urn:SmartConnection_v3">
<ea:Story ea:GUID="D8BEFD6C-AB31-4B0E-98BF-7348968795E1" pi0="style=&quot;50&quot; type=&quot;snippet&quot; readerVersion=&quot;6.0&quot; featureSet=&quot;257&quot; product=&quot;8.0(370)&quot; " pi1="SnippetType=&quot;InCopyInterchange&quot;">
<ea:StoryInfo>
<ea:SI_EL>headline</ea:SI_EL>
<ea:SI_Words>4</ea:SI_Words>
<ea:SI_Chars>20</ea:SI_Chars>
<ea:SI_Paras>1</ea:SI_Paras>
<ea:SI_Lines>1</ea:SI_Lines>
<ea:SI_Snippet>THIS IS THE HEADLINE</ea:SI_Snippet>
<ea:SI_Version>AB86A3CA-CEBC-49AA-A334-29641B95748D</ea:SI_Version>
</ea:StoryInfo>
</ea:Story>
</ea:Stories>

正如您所看到的,所有元素都有"ea:",这是一个名称空间前缀。

我正在编写一个XSLT文件来显示SI_Snippet文本,即"这是标题"。

如何在XSLT文件中写入xpath?它应该包含命名空间还是应该被排除在外?

//ea:Story[ea:SI_EL='headline']/ea:SI_Snippet or 
//Story[SI_EL='headline']/SI_Snippet

事实上,在我使用的在线工具中,两者都失败了:http://xslt.online-toolz.com/tools/xslt-transformation.php

所以应该有另一种方法吗?

如果稍后,它如何知道要查看哪个命名空间?我应该在运行时将命名空间传递给XslTransformer吗?

您应该在XSLT中声明名称空间,然后使用您给它的前缀:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ea="urn:SmartConnection_v3">
    <xsl:template match="/">
       <xsl:value-of select="//ea:Story[ea:SI_EL='headline']/ea:SI_Snippet" />
    </xsl:template>
    <!-- ...  -->
</xsl:stylesheet>

注意根元素中的xmlns:ea="urn:SmartConnection_v3"。这很重要。

是否尝试使用XDocument

var xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<ea:Stories ea:WWVersion=""2.0"" xmlns:aic=""http://ns.adobe.com/AdobeInCopy/2.0"" xmlns:ea=""urn:SmartConnection_v3"">
<ea:Story ea:GUID=""D8BEFD6C-AB31-4B0E-98BF-7348968795E1"" pi0=""style=&quot;50&quot; type=&quot;snippet&quot; readerVersion=&quot;6.0&quot; featureSet=&quot;257&quot; product=&quot;8.0(370)&quot; "" pi1=""SnippetType=&quot;InCopyInterchange&quot;"">
<ea:StoryInfo>
<ea:SI_EL>headline</ea:SI_EL>
<ea:SI_Words>4</ea:SI_Words>
<ea:SI_Chars>20</ea:SI_Chars>
<ea:SI_Paras>1</ea:SI_Paras>
<ea:SI_Lines>1</ea:SI_Lines>
<ea:SI_Snippet>THIS IS THE HEADLINE</ea:SI_Snippet>
<ea:SI_Version>AB86A3CA-CEBC-49AA-A334-29641B95748D</ea:SI_Version>
</ea:StoryInfo>
</ea:Story>
</ea:Stories>";
XDocument xdoc = XDocument.Parse(xml.ToString());
XElement v = xdoc.Descendants().FirstOrDefault(x => x.Name.LocalName == "SI_Snippet");

编辑

XPathNavigator navigator = xmldDoc.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
ns.AddNamespace("ea", "urn:SmartConnection_v3");
var v = xmlDoc.SelectSingleNode("//ea:SI_Snippet", ns);

最新更新