如何寫如下樣子的XML?用XMLwriter。
<?xml version="1.0" encoding="utf-8"?>
<book title="xxxx">
<bookinfoFONT-FAMILY: 新細明體; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">張">
</bookinfo>
<bookauthorinfo author="李">
</bookauthorinfo>
</book>
需要寫成與上面樣式一模一樣的XML檔。
最佳答案
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);
//生成BookInfo節點
System.Xml.XmlNode BookInfo = doc.CreateNode("element", "BookInfo", "");
//BookInfo增加attronwer屬性
XmlAttribute attronwer = doc.CreateAttribute("attronwer");
attronwer.Value = "張";
BookInfo.Attributes.SetNamedItem(attronwer);
//BookInfo增加class
XmlAttribute attrclass = doc.CreateAttribute("class");
attrclass.Value = "xxxx";
BookInfo.Attributes.SetNamedItem(attrclass);
//BookInfo節點加到根節點Book的子節點裏
root1.AppendChild(BookInfo);
System.Xml.XmlNode BookAuthorInfo = doc.CreateNode("element", "BookAuthorInfo", "");
XmlAttribute attrClass2 = doc.CreateAttribute("Class");
attrClass2.Value = "張";
BookAuthorInfo.Attributes.SetNamedItem(attrClass2);
XmlAttribute attrAuthor = doc.CreateAttribute("Author");
attrAuthor.Value = "xxxx";
BookAuthorInfo.Attributes.SetNamedItem(attrAuthor);
root1.AppendChild(BookAuthorInfo);
//保存XML文檔
doc.Save("2.xml");
如何建立XML CDATA元素
使用 XMLDocument
string myXml =
@"<!--?xml version='1.0' encoding='utf-8'?-->
<workingset>
<data>
</data>
</workingset>";
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(myXml);
XmlNode target = doc1.SelectSingleNode("WorkingSet/Data");
if (target != null)
target.AppendChild(doc1.CreateCDataSection("
<customertag>Hello</customertag>
"));
使用 XDocument
XDocument doc = XDocument.Parse(myXml, LoadOptions.SetLineInfo);
XElement dataNode = doc.Descendants("Data").First();
dataNode.Add(new XCData("
<customertag>Hello</customertag>
Console.WriteLine(doc.ToString());
結果
view source
print?
<!--?xml version="1.0" encoding="utf-8"?-->
<workingset>
<data><!--[CDATA[<customertag-->Hello]]></data>
</workingset>
全站熱搜
留言列表