通常的方式,我编写XML文件的代码是,
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("Products.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("Product");
writer.WriteAttributeString("ID", "001");
writer.WriteAttributeString("Name", "Keyboard");
writer.WriteElementString("Price", "10.00");
writer.WriteStartElement("OtherDetails");
writer.WriteElementString("BrandName", "X Keyboard");
writer.WriteElementString("Manufacturer", "X Company");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
但是上面的代码给了我一个不同的XML结构,如果我需要输出如下给定结构,如何编码,
<Books>
<Book ISBN="0553212419">
<title>Sherlock Holmes</title>
<author>Sir Arthur Conan Doyle</author>
</Book>
<Book ISBN="0743273567">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</Book>
<Book ISBN="0684826976">
<title>Undaunted Courage</title>
<author>Stephen E. Ambrose</author>
</Book>
<Book ISBN="0743203178">
<title>Nothing Like It In the World</title>
<author>Stephen E. Ambrose</author>
</Book>
</Books>
由于
答案 0 :(得分:10)
正如评论所述,只需修改已有的代码来编写正确的元素。
XmlWriter writer = XmlWriter.Create(@"Products.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("Books");
writer.WriteStartElement("Book");
writer.WriteAttributeString("ISBN", "0553212419");
writer.WriteElementString("Title", "Sherlock Holmes");
writer.WriteElementString("Author", "Sir Arthur Conan Doyle");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
洗涤,冲洗,重复。我建议写一个方法来添加每本书。
编辑 - 撰写书籍的方法
void WriteBookData(XmlWriter writer, string isbn, string title, string author)
{
writer.WriteStartElement("Book");
writer.WriteAttributeString("ISBN", isbn);
writer.WriteElementString("Title", title);
writer.WriteElementString("Author", author);
writer.WriteEndElement();
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(@"Products.xml", settings))
{
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("Books");
WriteBookData(writer, "0553212419", "Sherlock Holmes", "Sir Arthur Conan Doyle");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
答案 1 :(得分:2)
为什么不将Linq用于XML。它非常直接且非常容易取消
string filename = string.Empty;
XElement res= new XElement ("Books",new XElement ("Book",new XAttribute ("ISBN","="+055321212),
new XElement ("Title","Sherlock Homes"),
new XElement ("author","Sir Arthur Conan")
)
);
res.Save(filename);
您可以使用foreach外观将硬编码值存储在上述语句中