C#XML可以';加载缩进值
下面的代码导致“根级别的数据无效。第1行,位置1。” 我喜欢保持代码缩进(linebreak),但仍然存在上述问题。我可以使用TextReader加载xml,但它会删除我不喜欢的缩进。若你们知道如何解决这个问题,请让我知道。谢谢C#XML可以';加载缩进值,c#,C#,下面的代码导致“根级别的数据无效。第1行,位置1。” 我喜欢保持代码缩进(linebreak),但仍然存在上述问题。我可以使用TextReader加载xml,但它会删除我不喜欢的缩进。若你们知道如何解决这个问题,请让我知道。谢谢 public XmlDocument MYXML() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Indent = false; wSettin
public XmlDocument MYXML()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = false;
wSettings.OmitXmlDeclaration = false;
MemoryStream ms = new MemoryStream();
XmlWriter xw = XmlWriter.Create(ms, wSettings);// Write Declaration
xw.WriteStartDocument();
// Write the root node
xw.WriteStartElement("Library");
// Write the books and the book elements
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Hardback");
xw.WriteEndAttribute();
xw.WriteStartElement("Title");
xw.WriteString("Door Number Three");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("O'Leary, Patrick");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();
// Close the document
xw.WriteEndDocument();
// Flush the write
xw.Flush();
Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);
//The next 3 line works fine but it will remove the Indent from the XmlWriterSettings
//TextReader tr = new StreamReader(ms);
//ms.Seek(0, SeekOrigin.Begin);
//xmlOutput = tr.ReadToEnd() + "";
//Can't nload the xmlOutput from buffer
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlOutput);
return xmldoc;
}
XmlWriter
正在向流写入utf-8字节顺序标记Encoding.UTF8.GetString
没有考虑到这一点(因为它只应该出现在文件中),因此字符串的第一个字符变成无效的、不可打印的字符,这就是XmlDocument.LoadXml阻塞的地方
编辑:因为您说过要创建一个XmlDocument以便可以重用它,所以我推荐以下方法之一:
XDocument
(我建议这样做)XmlWriter writer=doc.CreateNavigator.AppendChild()
)请注意,您不能轻易地将不重要的空白添加到XmlDocument中。使用
XDocument
并使用doc.Save(Response.output)将其写入输出
是目前为止最简单的选择,如果您想获得格式良好的输出。整个编码循环的目的是什么?我真的需要将xml加载到XMLDocument中,因为我需要返回XMLDocument,这样它可以在多个区域中重用,并且更易于操作。我真的需要将xml加载到XMLDocument,因为我需要返回XMLDocument,以便在多个区域中重用它,并使其更易于操作。在这种情况下,通过创建节点和附加子节点直接创建XMLDocument
。或者,如果这是.Net 3.5或更高版本,请使用更易于使用的XDocument
。先将其写入字符串,然后再对其进行解析是不必要的浪费(尽管为了将来的参考,如果必须将XML写入字符串,请不要使用MemoryStream
,创建一个XmlWriter
,它将写入StringBuilder
或StringWriter
,但我还是不建议在这里这样做)。