在.NET读取XML文件,并选择节点节点、文件、NET、XML

由网友(幸福化为乌有)分享简介:我有很多很多树节点较重的XML文件。我需要接一些特殊的节点(例如说饮食),旗下有多个部分。IE浏览器。随机出现在XML饮食节点,所以我需要找到该节点作为饮食,并得到其子元素,并将其保存到数据库。假设饮食不仅是一条线,它有它下面的10-12项(可能是我可以用InnerXML得到它的内容,但真的不能用线节点线)解决方案...

我有很多很多树节点较重的XML文件。我需要接一些特殊的节点(例如说饮食),旗下有多个部分。

IE浏览器。随机出现在XML饮食节点,所以我需要找到该节点作为饮食,并得到其子元素,并将其保存到数据库。

假设饮食不仅是一条线,它有它下面的10-12项(可能是我可以用InnerXML得到它的内容,但真的不能用线节点线)

解决方案 确保您已添加引用System.Xml.Linq的。

吸出所有的饮食元素:

 的XElement wholeFile = XElement.Load(@C: DietSampleXML.xml);
IEnumerable的<的XElement> dietElements = wholeFile.Descendants(饮食);
 

如果您设置一个断点,将鼠标悬停在dietElements,然后单击查看结果,你会看到所有的饮食元素及其内部的XML。

asp.net如何读取XML文件

现在通过dietElements迭代添加的每个元素和/或子女到数据库的foreach(的XElement的X dietElements){...}

我测试用下面的XML:

 < XML版本=1.0编码=UTF-8&GT?;
< TestElement>
  <饮食>
    <名称>&阿特金斯LT; /名称>
    &其中; Colories> 1000℃; / Colories>
  < /节食>
  < TestElement2>
    <饮食>
      <名称>甜甜圈只有< /名称>
      <卡路里> 1500< /卡路里>
    < /节食>
  < / TestElement2>
  < TestElement3>
    < TestElement4>
      <饮食>
        <名称>&素食LT; /名称>
        &其中;卡路里> 500℃; /卡路里>
      < /节食>
    < / TestElement4>
  < / TestElement3>
< / TestElement>
 

I have a heavier XML file with lots and lots of tree nodes. I need to pick-up some particular node (for example say Diet), under which there are multiple sections.

ie. Diet node occurs randomly in the XML, so i need to find the node as Diet and get its child elements and save it to DB.

Assume that Diet is not only one line, it has 10-12 entries underneath it (may be i can get its contents using InnerXML, but really can't get line by line nodes)

解决方案

Make sure you have added a reference to "System.xml.Linq'.

Suck out all the Diet elements:

XElement wholeFile = XElement.Load(@"C:DietSampleXML.xml");
IEnumerable<XElement> dietElements = wholeFile.Descendants("Diet");

If you set a breakpoint and hover the mouse over "dietElements" and click "Results View", you will see all the Diet elements and their inner xml.

Now iterate through dietElements to add each element and/or children to your database: "foreach (XElement x in dietElements) { ... }"

I tested this with the following xml:

<?xml version="1.0" encoding="utf-8" ?>
<TestElement>
  <Diet>
    <Name>Atkins</Name>
    <Colories>1000</Colories>
  </Diet>
  <TestElement2>
    <Diet>
      <Name>Donuts Only</Name>
      <Calories>1500</Calories>
    </Diet>
  </TestElement2>
  <TestElement3>
    <TestElement4>
      <Diet>
        <Name>Vegetarian</Name>
        <Calories>500</Calories>
      </Diet>
    </TestElement4>
  </TestElement3>
</TestElement>

阅读全文

相关推荐

最新文章