我正在尝试将类型为XmlDocument
的对象转换为String。
在Visual Studio 2010中,只需按照文档here调用XmlDocument.InnerText
即可。
在新的.NET框架中XmlDocument.InnerText
已停止使用,现在根据文档here引发异常。
我只是使用XmlDocument.InnerXml
,因为这会返回一个String,但问题是返回的字符串不包含任何xml文档格式(换行符,缩进等)。遗产XmlDocument.InnerText
确实返回了所有这些。
看起来XmlDocument.InnerText
仍可用于节点和XmlElements
,但我想知道将整个XmlDocument
作为文本的最简单方法是什么。
答案 0 :(得分:1)
您可以使用StringWriter ...
完成此操作 ' build an XML document to test
Dim x As New System.Text.StringBuilder
With x
.AppendLine("<root>")
.AppendLine("<foo>bar</foo>")
.AppendLine("</root>")
End With
Dim d As New XmlDocument
d.LoadXml(x.ToString)
' create a stringwriter
Dim sw As New System.IO.StringWriter
' write the xml to the stringwriter
d.Save(sw)
' get the contents of the stringwriter with whitespace and line breaks preserved
Debug.WriteLine(sw.ToString)