XmlWriter.WriteStartDocument()未将声明输出到文件

时间:2013-08-07 10:14:01

标签: c# xml xmlreader xmlwriter

好的,我有一个方法应该读取XML文档,然后将它们全部包装在更大的XML文档中。

<Elements>
    <Element>
    <Element>
</Elements>

问题是当使用下面的代码时,输​​出文件缺少声明

<?xml >

这是为什么?我希望这是我想念的蠢事。

XmlWriter xmlWriter = XmlWriter.Create(outputFileName, xwsSettings);

xmlWriter.WriteStartDocument();

xmlWriter.WriteStartElement("Elements");

foreach (var item in items)
{
    xmlReader = XmlReader.Create(item.FullFilename);

    while (xmlReader.Read())
    {
        if(xmlReader.NodeType == XmlNodeType.Element)
        {
            xmlWriter.WriteRaw(xmlReader.ReadOuterXml());
            break;
  }
    }
}

xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();

xmlWriter.Flush();
xmlWriter.Close();
xmlWriter = null;

1 个答案:

答案 0 :(得分:3)

正如@Tim强调要检查我的XmlWriterSettings设置不正确

XmlWriterSettings xwsSettings = new XmlWriterSettings();
xwsSettings.CheckCharacters = false;
xwsSettings.CloseOutput = true;
xwsSettings.ConformanceLevel = ConformanceLevel.Document;
xwsSettings.Encoding = Encoding.UTF8;
xwsSettings.Indent = false;
xwsSettings.NewLineHandling = NewLineHandling.None;

xwsSettings.OmitXmlDeclaration = true; <---- should have been false;