刚刚接触XML文件读写,用xmlTextWriter,部分代码见下面
string strFileName = @"f:\test.xml";
XmlTextWriter xmlTextWriter = new XmlTextWriter(strFileName, null);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument(); xmlTextWriter.WriteStartElement("Root");
xmlTextWriter.WriteElementString("child1", "child1"); xmlTextWriter.WriteStartElement("child1");
xmlTextWriter.WriteString("child1");
xmlTextWriter.WriteEndElement(); ......
我想问各位的是,用WriteElementString(红色的)方法和用WriteStartElment(绿色的)方法有什么区别,何时使用。
另外我运行过两个生成出来的节点是一摸一样的,但是好像用WriteElementString就不能用WriteAttributeString写属性了,我在MSDN上看到了有一个WriteAttributes方法好像但是里面参数好像不是写一个string的,望各位帮忙解答。
string strFileName = @"f:\test.xml";
XmlTextWriter xmlTextWriter = new XmlTextWriter(strFileName, null);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument(); xmlTextWriter.WriteStartElement("Root");
xmlTextWriter.WriteElementString("child1", "child1"); xmlTextWriter.WriteStartElement("child1");
xmlTextWriter.WriteString("child1");
xmlTextWriter.WriteEndElement(); ......
我想问各位的是,用WriteElementString(红色的)方法和用WriteStartElment(绿色的)方法有什么区别,何时使用。
另外我运行过两个生成出来的节点是一摸一样的,但是好像用WriteElementString就不能用WriteAttributeString写属性了,我在MSDN上看到了有一个WriteAttributes方法好像但是里面参数好像不是写一个string的,望各位帮忙解答。
using System.IO;
using System.Xml; public class Sample
{
private const string m_Document = "sampledata.xml"; public static void Main() { XmlWriter writer = null; try { XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
writer = XmlWriter.Create (m_Document, settings); writer.WriteComment("sample XML fragment"); // Write an element (this one is the root).
writer.WriteStartElement("book"); // Write the namespace declaration.
writer.WriteAttributeString("xmlns", "bk", null, "urn:samples"); // Write the genre attribute.
writer.WriteAttributeString("genre", "novel"); // Write the title.
writer.WriteStartElement("title");
writer.WriteString("The Handmaid's Tale");
writer.WriteEndElement(); // Write the price.
writer.WriteElementString("price", "19.95"); // Lookup the prefix and write the ISBN element.
string prefix = writer.LookupPrefix("urn:samples");
writer.WriteStartElement(prefix, "ISBN", "urn:samples");
writer.WriteString("1-861003-78");
writer.WriteEndElement(); // Write the style element (shows a different way to handle prefixes).
writer.WriteElementString("style", "urn:samples", "hardcover"); // Write the close tag for the root element.
writer.WriteEndElement(); // Write the XML to file and close the writer.
writer.Flush();
writer.Close();
} finally {
if (writer != null)
writer.Close();
}
} }