在.NET读取XML文件,并选择节点 [英] Reading an XML File and Selecting Nodes in .NET

查看:379
本文介绍了在.NET读取XML文件,并选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案
  1. 确保您已添加引用System.Xml.Linq的。
  2. 吸出所有的饮食元素:

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

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

  4. 现在通过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)

解决方案

  1. Make sure you have added a reference to "System.xml.Linq'.
  2. Suck out all the Diet elements:

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

  3. 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.

  4. 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>

这篇关于在.NET读取XML文件,并选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆