Linq To Xml 用VS编写Xml文件
2013-07-21 23:55
330 查看
下面的代码创建一个 XDocument 对象及其关联的包含对象。
检查文件 test.xml 时, 会得到以下输出:
构造 XML 树
另一个创建 XML 树的十分常用的方法是使用 LINQ 查询的结果来填充 XML 树,如下面的示例所示:
此示例产生以下输出:
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>
相关文章推荐
- linq to xml 简单的增、删、改、查、保存xml文件操作
- 步步为营VS 2008 + .NET 3.5(14) - XLINQ(LINQ to XML)之针对XML文件的添加、查询、更新和删除
- 1.4.2 用LINQ to XML 对 XML 文件进行处理
- 提交了 VS 2008 sp1 对 Linq to SQL 的 xml 字段类型支持的一个 bug
- c# comboBox 使用 linq to xml 绑定 XML文件
- 提交了 VS 2008 sp1 对 Linq to SQL 的 xml 字段类型支持的一个 bug
- hibernate mapping文件中 xmlns会导致linq to xml 查询不到对应的节点
- Linq to Oracle 使用教程(五)使用 Xml 映射文件
- Linq to xml 读取xml文件
- LinqToXML~读XML文件续
- Linq to Xml,从其他xml文件读取节点(Element和Text混合)插入当前xml文件, 尖括号不转义
- 步步为营VS 2008 + .NET 3.5(14) - XLINQ(LINQ to XML)之针对XML文件的添加、查询、更新和删除
- 步步为营VS 2008 + .NET 3.5(14) - XLINQ(LINQ to XML)之针对XML文件的添加、查询、更新和删除
- LinQ To XML 新建文件并增加节点
- linq to xml 简单的增、删、改、查、保存xml文件操作
- 使用Linq to Xml 读取配置文件
- c#中使用linq to xml 访问 xml文件
- 步步为营VS 2008 + .NET 3.5(14) - XLINQ(LINQ to XML)之针对XML文件的添加、查询、更新和删除
- 使用Linq to Xml 读取配置文件