XElement.WriteTo(XmlWriter)和XElement.Save(XmlWriter)有什么区别?

时间:2018-09-28 09:38:04

标签: .net xml linq-to-xml

1 个答案:

答案 0 :(得分:1)

XElement.Save(XmlWriter) 将完整的xml文档写入目标XmlWriter,包括开始和结束文档声明。
要编写XElement本身的内容,它调用相同的WriteTo方法。

来自.NET reference source

public void Save(XmlWriter writer)
{
    if (writer == null)
    {
        throw new ArgumentNullException("writer");
    }
    writer.WriteStartDocument();
    WriteTo(writer);
    writer.WriteEndDocument();
}


XElement.WriteTo(XmlWriter) 只是将给定的XElement写入目标XmlWriter

来自.NET reference source

public override void WriteTo(XmlWriter writer)
{
    if (writer == null)
    {
        throw new ArgumentNullException("writer");
    }
    new ElementWriter(writer).WriteElement(this);
}

这允许XElement被包含在已经包含任何其他xml节点的XmlWriter中,例如。自定义根xml元素,如下所示。
同样,可以在同一个XElement.WriteTo上进行多个XmlWriter呼叫。

XElement xml = XElement.Parse("<foo>bar</foo>");

StringBuilder builder = new StringBuilder();    
using (XmlWriter writer = XmlWriter.Create(builder))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("root");

    xml.WriteTo(writer);

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

Console.WriteLine(builder.ToString());

以上结果为:

<?xml version="1.0" encoding="utf-16"?>
<root>
   <foo>bar</foo>
</root>