在C#中使用XElement读取XML

在C#中使用XElement读取XML

本文介绍了在C#中使用XElement读取XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





i我在c#中使用xml

i希望使用XElement读取xml

我的Xml文件是这样的

Hi

i am working with xml in c#
i want to read the xml using XElement
My Xml file is like this

<?xml version="1.0" encoding="UTF-8"?><!--XML GENERATED by IntuitDataSyncEngine (IDS) using \\SBDomainServices\CDM\branches\3.9.0-rel-1-->
<RestResponse xmlns="http://www.intuit.com/sb/cdm/v2"
xmlns:xdb          ="http://xmlns.oracle.com/xdb"
xmlns:xsi          ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.intuit.com/sb/cdm/v2 ../common/RestDataFilter.xsd">
<Items>
<Item>
<Name>139</Name>
<Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
<Item>
<Name>139</Name>
<Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
</Item>
<Item>
<Name>139</Name>
<Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
</Item>
</RestResponse>





来自这个xml我希望阅读物品

< RestResponse> 中节点我可以轻松地读取项目

但是< RestResponse>我无法使用XElement阅读项目

如何阅读项目..?说一些答案



from this xml i want the read the items
without "<RestResponse>" node i can easily read the item
but with "<RestResponse>" i can''t read the item using XElement
How to read the Items ..? say some Answers

推荐答案



// InputXML is the XML as a string. Use XDocument.Load() for file/stream input.
XDocument source = XDocument.Parse(InputXML);
XName itemName = XName.Get("Item", source.Root.Name.NamespaceName);
foreach (XElement item in source.Descendants(itemName))
{
  Console.WriteLine(item.ToString());
}



此输出:


This outputs:

<Item xmlns="http://www.intuit.com/sb/cdm/v2">
  <Name>139</Name>
  <Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
</Item>
<Item xmlns="http://www.intuit.com/sb/cdm/v2">
  <Name>139</Name>
  <Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
</Item>
<Item xmlns="http://www.intuit.com/sb/cdm/v2">
  <Name>139</Name>
  <Desc>[Sample Product] Elgato EyeTV DTT Deluxe</Desc>
</Item>



请注意输出中的显式命名空间属性。


Note the explicit namespace attribute in the output.


这篇关于在C#中使用XElement读取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:15