如何写平级的2个带Attribute的XML Element?

来源:百度知道 编辑:UC知道 时间:2024/06/14 15:19:11
如何写如下样子的XML?用XMLwriter。

<?xml version="1.0" encoding="utf-8" ?>
<Book id = "99" title = "xxxx">
<BookInfo onwer = "张" class = "S" />
<BookAuthorInfo Class = "bbbb" Author = "李" />
</Book>

需要写成与上面样式一模一样的XML文件。
C# winform。
谢谢!
1. <BookInfo /> 和<BookAuthorInfo />元素,平级显示,而他们2个是<Book>元素的子元素。
2. 同时<BookInfo>和<BookAuthorInfo>元素都不显示</BookInfo>和</BookAuthorInfo>,而按照如上样式显示。
3. 用XMLwriter!
谢谢 kingson88。我需要一个用XMLwrite写出来的代码。

System.Xml.XmlDocument doc = new XmlDocument();
XmlDeclaration xmldecl;

//添加XML的声明
xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);

System.Xml.XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);

//NEW Book跟节点
System.Xml.XmlNode root1 = doc.CreateNode("element", "Book", "");
//跟节点加到XML中去
doc.AppendChild(root1);

//跟节点添加id属性
XmlAttribute attrid = doc.CreateAttribute("id");
attrid.Value = "99";
root1.Attributes.SetNamedItem(attrid);

//跟节点添加title属性
XmlAttribute attrtitle = doc.CreateAttribute("title");
attrtitle.Value = "xxxx";
root1.Attributes.SetNamedItem(attrtitle);