【问题标题】:Using XmlDocument Class to create Xml tags with whitespaces使用 XmlDocument 类创建带有空格的 Xml 标记
【发布时间】:2019-05-21 15:35:52
【问题描述】:

我正在使用XmlDocument Class 创建一个不合规的 XML 文档,其中 XML 标记内有一些空格。

目的是创建这样的标签:

<name TYPE="Text">Hey</name>

代码:

Dim customNodeName = Tag & " TYPE = " & typestr & ""
Dim customNode As XmlNode = doc.CreateNode("element", customNodeName, "")

所以当我调试我的代码时

 System.Xml.XmlException
 ' ' character, hexadecimal value 0x20

被抛出。

有没有可能的解决方法?

【问题讨论】:

  • 如果您使用的是 VB,我会使用 XElement。我将发布一个答案,向您展示使用 XElement 的效果。

标签: xml vb.net xmldocument


【解决方案1】:

使用下面的代码进行测试。另外,导入 System.Xml :)

    ' Just used console app for demo purposes
Sub Main()
    ' Create an XmlDocument to house the stuff
    Dim doc As New XmlDocument

    ' Create your root element
    Dim root As XmlElement = doc.CreateElement("root")

    ' Create your 'name' element
    Dim name As XmlElement = doc.CreateElement("name")

    ' Set the attribute of 'name' to nothing as your example has.
    name.SetAttribute("Type", "Text")

    ' Set the innerText of your name element as your example has.
    name.InnerText = "Hey"

    ' Append your creations
    root.AppendChild(name)
    doc.AppendChild(root)

    ' This is only here for review
    doc.Save("C:\Temp\Test.xml")
End Sub

上面的代码将产生:

【讨论】:

    【解决方案2】:

    由于您已标记此 VB,请使用 XElement。

        Dim xe As XElement = <root></root>
        xe.Add(<name TYPE="Text">Hey</name>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 2019-03-17
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多