2013-02-05 66 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

相關問題