Linq To Xml 用VS编写Xml文件

下面的代码创建一个 XDocument 对象及其关联的包含对象。

using System.Xml.Linq;
XDocument d = new XDocument( 
  new XComment("This is a comment."), 
  new XProcessingInstruction("xml-stylesheet", "href='mystyle.css' title='Compact' type='text/css'"), 
  new XElement("Pubs", 
  new XElement("Book", 
  new XElement("Title", "Artifacts of Roman Civilization"), 
  new XElement("Author", "Moreno, Jordao") 
  ), 
  new XElement("Book", 
  new XElement("Title", "Midieval Tools and Implements"), 
  new XElement("Author", "Gazit, Inbar") 
  ) 
  ), 
  new XComment("This is another comment.") 
  ); 
  d.Declaration = new XDeclaration("1.0", "utf-8", "true"); 
  Console.WriteLine(d); 
  d.Save("test.xml");

检查文件 test.xml 时, 会得到以下输出:

<?xml version="1.0" encoding="utf-8"?>
<!--This is a comment.-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs>
  <Book>
    <Title>Artifacts of Roman Civilization</Title>
    <Author>Moreno, Jordao</Author>
  </Book>
  <Book>
    <Title>Midieval Tools and Implements</Title>
    <Author>Gazit, Inbar</Author>
  </Book>
</Pubs>
<!--This is another comment.-->

构造 XML 树

  XElement contacts = 
  new XElement("Contacts", 
  new XElement("Contact", 
  new XElement("Name", "Patrick Hines"), 
  new XElement("Phone", "206-555-0144"), 
  new XElement("Address", 
  new XElement("Street1", "123 Main St"), 
  new XElement("City", "Mercer Island"), 
  new XElement("State", "WA"), 
  new XElement("Postal", "68042") 
  ) 
  ) 
  );

另一个创建 XML 树的十分常用的方法是使用 LINQ 查询的结果来填充 XML 树,如下面的示例所示:

XElement srcTree = new XElement("Root", 
  new XElement("Element", 1), 
  new XElement("Element", 2), 
  new XElement("Element", 3), 
  new XElement("Element", 4), 
  new XElement("Element", 5) 
  ); 
  XElement xmlTree = new XElement("Root", 
  new XElement("Child", 1), 
  new XElement("Child", 2), 
  from el in srcTree.Elements() 
  where (int)el > 2 
  select el 
  ); 
  Console.WriteLine(xmlTree);

此示例产生以下输出:

<Root>
  <Child>1</Child>
  <Child>2</Child>
  <Element>3</Element>
  <Element>4</Element>
  <Element>5</Element>
</Root>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值