【问题标题】:parse an xml file without changing the encoding and preserving the file format解析 xml 文件而不更改编码并保留文件格式
【发布时间】:2014-04-21 15:23:35
【问题描述】:

原始xml文件用UTF-8 without BOM编码

<?xml version="1.0" encoding="UTF-8"?>
<some_text>
    <ada/>
    <file/>
    <title><![CDATA[]]></title>
    <code/>
    <parathrhseis/>
</some_text>

我尝试在此函数中将文本设置为title

Dim myXmlDocument As XmlDocument = New XmlDocument()
Dim node As XmlNode
Dim s As String

s = "name.xml"
If System.IO.File.Exists(s) = False Then
    Return False
End If

myXmlDocument.Load(s)
node = myXmlDocument.DocumentElement

Try
    For Each node In node.ChildNodes
        If node.Name = "title" Then
            node.FirstChild.InnerText = "text"
            Exit For
        End If
    Next

    myXmlDocument.Save(s)
Catch e As Exception
        MsgBox("Error in XmlParsing: " + e.Message)
        Return False
End Try

Return True

文本写入正确,但编码更改为UTF-8 with BOM,它也是
添加空格:

<?xml version="1.0" encoding="UTF-8"?>
<some_text>
    <ada /> <- here
    <file /> <- here
    <title><![CDATA[text]]></title>
    <code /> <- here
    <parathrhseis /> <- here
</some_text>

我该如何解决这些问题

解决方案(在 Bradley Uffner 的帮助下)

Dim fileReader As String

Try
    fileReader = My.Computer.FileSystem.ReadAllText("original.xml")

    fileReader = fileReader.Replace("<ada />", "<ada/>")
    fileReader = fileReader.Replace("<file />", "<file/>")
    fileReader = fileReader.Replace("<code />", "<code/>")
    fileReader = fileReader.Replace("<parathrhseis />", "<parathrhseis/>")

    File.WriteAllText("copy.xml", fileReader) <- File.WriteAllText automatically stores it without the BOM
Catch ex As Exception
    MsgBox("Error: " + ex.Message)

    Return
End Try

【问题讨论】:

    标签: xml vb.net encoding


    【解决方案1】:

    这实际上不是解析文件的问题,而是保存文件的问题。

    查看这篇文章了解如何在没有 BOM 的情况下保存 xml。 XDocument: saving XML to file without BOM

    相关代码为:

    Using writer = New XmlTextWriter(".\file.xml", New UTF8Encoding(False))
        doc.Save(writer)
    End Using
    

    通常,您可以通过 XmlTextWriter 的 .Settings 属性控制文档的格式,但我没有看到用于控制自闭合元素间距的属性。通过将输出保存到流并手动删除“/>”之前的所有空格,您可能会在保存到文件系统之前对输出进行更好的后处理。

    【讨论】:

    • 这就是我现在想要做的。手动删除空格。使用XmlTextWriter 解决了编码问题,但它也将文本UTF-8 更改为utf-8!我也必须改变它。
    • 只是出于好奇,为什么格式要求这么严格?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多