Linq To Xml 用VS编写Xml文件
发布时间:2020-12-15 23:36:41 所属栏目:百科 来源:网络整理
导读:下面的代码创建一个 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'")
下面的代码创建一个 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") ),"Midieval Tools and Implements"),"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),2),3),4),5) ); XElement xmlTree = new XElement("Root", new XElement("Child", 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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |