2015-05-29 50 views
2
<channel> 
     <title>test + test</title> 
     <link>http://testprog.test.net/api/test</link> 
     <description>test.com</description> 
     <category>test + test</category> 

     <item xml:base="http://test.com/test.html?id=25> 
      <guid isPermaLink="false">25</guid> 
      <link>http://test.com/link.html</link> 
      <title>title test</title> 
      <description>Description test description test</description> 
      <a10:updated>2015-05-26T10:23:53Z</a10:updated> 
      <enclosure type="" url="http://test.com/test/test.jpg" width="200" height="200"/> 
     </item> 
    </channel> 

如何使用c#從標記xml中提取屬性?

我提取此標記(職稱考試)是這樣的:

title = ds.Tables["item"].Rows[0]["title"] as string; 

如何從<encosure>標籤用C#中提取url屬性?

THX

+0

能否請您澄清 - 你如何顯示'ds.Tables ...'這段代碼與你顯示的xml有關?它與一些'DataTable'有關,不是xml,我想。 –

+0

創建兩個類(通道和項目),向成員(屬性或元素)添加適當的xml標籤並反序列化對象 –

回答

0

第一選項

您可以創建類映射和反序列化XML到對象,並容易作爲屬性訪問。

第二個選項

如果你只對少數值感興趣,你不希望創建映射類,你可以使用XPath,有很多文章和問題anwered,你可以很容易找到。

從標籤中提取url屬性,你可以使用路徑:

"/channel/item/enclosure/param[@name='url']/@value" 
0

有很多很多的文章,將幫助您讀取XML,但是簡單的答案是將XML加載到一個XML文件,並且只需致電

doc.GetElementsByTagName("enclosure") 

這將返回一個XmlNodeList,其中包含在您的文檔中找到的所有'enclosure'標記。我真的會推薦閱讀關於使用XML來確保您的應用程序功能強大。

0

您可以使用LinqToXML,這將更好地爲您有用...

請參閱代碼

string xml = @"<channel> 
      <title>test + test</title> 
      <link>http://testprog.test.net/api/test</link> 
      <description>test.com</description> 
      <category>test + test</category> 

      <item xml:base=""http://test.com/test.html?id=25""> 
       <guid isPermaLink=""false"">25</guid> 
       <link>http://test.com/link.html</link> 
       <title>title test</title> 
       <description>Description test description test</description> 
       <a10>2015-05-26T10:23:53Z</a10> 
       <enclosure type="""" url=""http://anupshah.com/test/test.jpg"" width=""200"" height=""200""/> 
      </item> 
     </channel>"; 

     var str = XElement.Parse(xml); 


     var result = (from myConfig in str.Elements("item") 
        select myConfig.Elements("enclosure").Attributes("url").SingleOrDefault()) 
        .First(); 

     Console.WriteLine(result.ToString()); 

我希望它會幫助你...

相關問題