Linq to XML Linq读取MXL(XDocument.Load()、XDocument.Parse()、XElement.Load()、XElement.Parse())

命名空间:

System.Xml.Linq

一、Linq读取XML

1、demo.xml

<?xml version="1.0" encoding="utf-8" ?>
<note>
  <conf>
    <to>infozero</to>
    <from>lerroy</from>
    <heading>测试信息</heading>
    <body>第一条测试信息</body>
    <title name="我的第一条消息">from myself</title>
  </conf>
  <conf>
    <to>infozero@163.com</to>
    <from>text</from>
    <heading> 时刻提醒我 </heading>
    <body>这是一条测试信息!</body>
    <title name="我的第二条消息">from others</title>
  </conf>
</note>

2、读取XML

XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("demo.xml"));
            var text = from t in doc.Descendants("conf")
                       .Where(w => w.Element("to").Value.Contains('@'))
                       select new
                       {
                           to = t.Element("to").Value,froms = t.Element("from").Value,body = t.Element("body").Value
                       };

            foreach (var a in text)
            {
                Response.Write(a.to+a.froms+a.body);
            }

二、加载和解析XML内容

string myElement = @"<Car id='3'>
                             <Color>Yellow</Color>
                             <Make>Yugo</Make>
                           </Car>";

            XElement newElemment = XElement.Parse(myElement);
            newElemment.Save(System.Web.HttpContext.Current.Server.MapPath("demo1.xml"));
           
            newElemment.Descendants("Color").Remove();//查询Color元素,并删除

newElemment.Descendants("Color").First().Value; //获取节点的值

三、XElement、XDocument 创建XML文档

//1、 XElement 创建XML文档
            XElement doc = new XElement("ProductsParameter",new XAttribute("ID","1000"),new XElement("Products",new XElement("PoductType","DTSD342-9N"),new XElement("Queries","00020004")),new XElement("Variable",new XElement("Ua",new XElement("ID","1"),new XElement("Name","Ua"),new XElement("Description","A相电压"),new XElement("VType","DL/T 645-1997"),new XElement("Link","DL_0_0_DCBA"),new XElement("Formula","2#主变_DLT97_380.Ua}*{2#主变_DLT97_380.PTRatio}/10000"),new XElement("Unit","kv"),new XElement("Digit","3"),new XElement("ZeroFloat","0"),new XElement("InitValue",new XElement("MaxValue","10000000000"),new XElement("MinValue","-10000000000"),new XElement("IsRecord","True"),new XElement("RecordCycle","300"),new XElement("IsBroken","False")
                    ))
                );

            string path = Environment.CurrentDirectory;
            doc.Save(string.Format(@"{0}\ProductsXML\DTSD342-9N.xml",path));


            //2、XDocument 创建XML文档
            XDocument Xdoc = new XDocument(
                //XDeclaration 指定版本,编码
                new XDeclaration("1.0","utf-8","yes"),new XComment("注释!"),//XProcessingInstruction XML处理指令
                new XProcessingInstruction("xml-stylesheet","href='MyStyles.css' title='Compact' type='text/css'"),new XElement("Inventory",new XElement("Car",1),new XElement("Color","Green"),new XElement("Make","BMW")
                                ),2),"Red"),"yugo"))
                        )       
                );

            Xdoc.Save(string.Format(@"{0}\ProductsXML\Inventory.xml",path));

生成XML文件
<?xml version="1.0" encoding="utf-8"?>
<ProductsParameter ID="1000">
  <Products>
    <PoductType>DTSD342-9N</PoductType>
    <Queries>00020004</Queries>
  </Products>
  <Variable>
    <Ua>
      <ID>1</ID>
      <Name>Ua</Name>
      <Description>A相电压</Description>
      <VType>DL/T 645-1997</VType>
      <Link>DL_0_0_DCBA</Link>
      <Formula>2#主变_DLT97_380.Ua}*{2#主变_DLT97_380.PTRatio}/10000</Formula>
      <Unit>kv</Unit>
      <Digit>3</Digit>
      <ZeroFloat>0</ZeroFloat>
      <InitValue>0</InitValue>
      <MaxValue>10000000000</MaxValue>
      <MinValue>-10000000000</MinValue>
      <IsRecord>True</IsRecord>
      <RecordCycle>300</RecordCycle>
      <IsBroken>False</IsBroken>
    </Ua>
  </Variable>
</ProductsParameter>

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--注释!-->
<?xml-stylesheet href='MyStyles.css' title='Compact' type='text/css'?>
<Inventory>
  <Car ID="1">
    <Color>Green</Color>
    <Make>BMW</Make>
  </Car>
  <Car ID="2">
    <Color>Red</Color>
    <Make>yugo</Make>
  </Car>
</Inventory>

XDocument 与XElement 区别?

二者在通过Load方法加载XML时,你会发现二者的区别:

简单概括就是:

XDocument.Load() 加载整个XML文档 包括根节点

XElement.Load()不会加载XML的根节点

XElement.Load()示例代码

File.WriteAllText("Test.xml",@"<Root>
    <Child1>1</Child1>
    <Child2>2</Child2>
    <Child3>3</Child3>
</Root>");

Console.WriteLine("Querying tree loaded with XElement.Load");
Console.WriteLine("----");
XElement doc = XElement.Load("Test.xml");
IEnumerable<XElement> childList =
    from el in doc.Elements()
    select el;
foreach (XElement e in childList)
    Console.WriteLine(e);

结果:

Querying tree loaded with XElement.Load
----
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>

XDocument.Load() 示例代码

File.WriteAllText("Test.xml",@"<Root>
    <Child1>1</Child1>
    <Child2>2</Child2>
    <Child3>3</Child3>
</Root>");

Console.WriteLine("Querying tree loaded with XDocument.Load");
Console.WriteLine("----");
XDocument doc = XDocument.Load("Test.xml");
IEnumerable<XElement> childList =
    from el in doc.Elements()
    select el;
foreach (XElement e in childList)
    Console.WriteLine(e);

结果:

Querying tree loaded with XDocument.Load
----
<Root>
  <Child1>1</Child1>
  <Child2>2</Child2>
  <Child3>3</Child3>
</Root>

四、将数组、ADO.NET、文件数据转换成XML

1、数组

//数组转换成XML
        static void MakeXElementFromArray()
        {
            var people = new[] { 
                new {FirstName="张三",Age=20},new {FirstName="李四",Age=20}
            };

            var arrayDataAsXElement = from c in people
                                      select
                                      new XElement("Person",new XAttribute("Age",c.Age),new XElement("FirstName",c.FirstName));
            XElement peopleDoc = new XElement("People",arrayDataAsXElement);
            Console.Write(peopleDoc);
        }


效果

<People>
  <Person Age="20">
    <FirstName>张三</FirstName>
  </Person>
  <Person Age="20">
    <FirstName>李四</FirstName>
  </Person>
</People>

相关文章

引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满足人的生产生活需要而产生的。具体...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满...
(点击上方公众号,可快速关注) 公众号:smart_android 作者:耿广龙|loonggg 点击“阅读原文”,可查看...
一、xml与xslt 相信所有人对xml都不陌生,其被广泛的应用于数据数据传输、保存与序列化中,是一种极为强...