2013-02-05 136 views
1

我有如下的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吗?

回答

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"在根元素。这个很重要。

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); 
+0

我明白你是否想要尖叫!但是我为这个项目使用了.NET 1.1,所以XDocument不存在,需要在XSLT中使用XPath。 –

+0

@TheLight根据我的答案OP的作品;)除此之外,尝试我的编辑? – LukeHennerley

相关问题