• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

详细Linq读取XML的展示代码

武飞扬头像
PHP中文网
帮助14

Linq To XML的核心类XElement,一个XElement表示一个节点,new XElement("Order"),创建一个名字为Order的标签,调用Add增加子节点,也是XElement 对象

下面是几种LINQ操作XML的常见形式。

///写文件(生成节点性质的)

XElement ePersons = new XElement("Persons");
XElement ptom = new XElement("Person"); //增加一个Person节点
ptom.Add(new XElement("Name", "Tom"));//在ptom下再增加子节点
ptom.Add(new XElement("Age", "18"));
ePersons.Add(ptom);
XElement pjack = new XElement("Person");
pjack.Add(new XElement("Name", "Jack"));
pjack.Add(new XElement("Age", "20"));
ePersons.Add(pjack);

最终生成:

Tom
18


Jack
20


///写文件(生成属性性质的)

 XElement ptom = new XElement("Person");
 ptom.Add(new XAttribute("Name", "tom"));//添加XAttribute就生成属性
 ptom.Add(new XAttribute("Age", "18"));
 ePersons.Add(ptom);

 XElement pjack = new XElement("Person");
 pjack.Add(new XAttribute("Name", "jack"));
 pjack.Add(new XAttribute("Age", "20"));
 ePersons.Add(pjack);

最终生成:

<Persons>
<Person Name="tom" Age="18"/>
<Person Name="jack" Age="20"/>
</Persons>

//读XML 读取节点格式的值

 XDocument xd= XDocument.Load("XML文件地址");

      foreach (XElement item in xd.Root.Descendants("Person"))//得到每一个Person节点,得到这个节点再取他的Name的这个节点的值
          {
             Console.WriteLine(item.Element("Age").Value);//Person的节点的下得节点为Name的
          }

注释:doc.root(得到根节点的XElement对象).XElement(“tagname”)方法得到的就是节点下第一个名字为tagname的节点。
如果doc.root。XElements(复数形式)就是得到所有的子节点,Descendants("“tagname”")子孙节点

//读XML 读取属性格式的值

 XDocument xd= XDocument.Load(@"D:\Program Files\Demo\Demo\ConsoleApplication2\XMLFile2.xml");
           foreach (XElement item in xd.Root.Descendants("Person"))//得到每一个Person节点,得到这个节点再取他的Name的这个节点的值
           {
               Console.WriteLine(item.Attribute("Age").Value);//Person的节点的下得节点为Name的
           }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbiefe
系列文章
更多 icon
同类精品
更多 icon
继续加载