XmlDocument.InnerText替换新.NET

时间:2018-02-02 14:47:55

标签: .net xml vb.net xmldocument

我正在尝试将类型为XmlDocument的对象转换为String。

在Visual Studio 2010中,只需按照文档here调用XmlDocument.InnerText即可。

在新的.NET框架中XmlDocument.InnerText已停止使用,现在根据文档here引发异常。

我只是使用XmlDocument.InnerXml,因为这会返回一个String,但问题是返回的字符串不包含任何xml文档格式(换行符,缩进等)。遗产XmlDocument.InnerText确实返回了所有这些。

看起来XmlDocument.InnerText仍可用于节点和XmlElements,但我想知道将整个XmlDocument作为文本的最简单方法是什么。

1 个答案:

答案 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)