如何在名称空间前缀的情况下找到Xml元素?

时间:2013-02-05 11:21:51

标签: c# asp.net xml xslt xpath

我有一个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吗?

2 个答案:

答案 0 :(得分:1)

您应该在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"。这很重要。

答案 1 :(得分:0)

尝试使用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);