【问题标题】:XML append attribute without creating a variableXML 附加属性而不创建变量
【发布时间】:2020-03-29 14:31:43
【问题描述】:

我试图在不声明变量的情况下在一行中实现以下代码。代码将创建一个 XML 元素,添加一个属性和一个值,最后将其附加到 XML 文档中:

    Dim XMLDoc As New XmlDocument
    Dim XMLRoot As XmlElement
    XMLRoot = XMLDoc.CreateElement("Test1")
    XMLRoot.Attributes.Append(XMLDoc.CreateAttribute("Test2")).Value = "Test3"
    XMLDoc.AppendChild(XMLRoot)

我尝试了以下方法,但它返回错误:Boolean cannot be convert to 'XmlNode'.

    Dim XMLDoc As New XmlDocument
    XMLDoc.AppendChild(XMLDoc.CreateElement("Test1").Attributes.Append(XMLDoc.CreateAttribute("Test2").Value = "Test3"))

这会返回错误:表达式不产生值。

    Dim XMLDoc As New XmlDocument
    XMLDoc.AppendChild(XMLDoc.CreateElement("Test1").SetAttribute("Test2", "Test3"))

【问题讨论】:

  • 即使您将变量创建内联到方法调用中,变量仍将由编译器创建。通过使用变量,您将使他人和以后的生活更轻松:)。为什么不想使用临时变量?
  • 我很好奇我将如何解决它。我找不到我的问题的解决方案。你会碰巧知道我这样做的方法吗?
  • 您需要创建一个变量,因为.AppendChild 方法需要XmlElement 类型的值。如果元素创建很复杂,用返回创建元素的方法包裹它并传递给.AppendChild()

标签: xml vb.net


【解决方案1】:

您似乎正在创建新的 xml 文档。在不引入“临时”变量的情况下,几乎没有其他选项可以创建 xml。

XDocument (System.Xml.Linq)

Dim document As New XDocument(
    new XElement(
        "root",
        new XElement(
            "element",
            new XAttribute("type", "parent")
        )
    )    
)

' Output

' <root>
'     <person type="parent" />
' </root>

使用 XML Literals 是一种仅存在于 VB.NET 中的功能,您可以以更方便的方式进行操作

Dim document As XDocument = 
    <?xml version="1.0"?>
    <root>
        <person type="parent"></person>
    </root>

' Output

' <root>
'      <person type="parent" />
' </root>

如果您需要将元素附加到现有的 xml 中:

使用 LINQ to XML

Dim document As XDocument = XDocument.Load(filepath)

document.Root.Add(new XElement("person", new XAttribute("type", "child")))

使用 XML 文字

Dim document As XDocument = XDocument.Load(filepath)

document.Root.Add(<person type="child"></person>)

【讨论】:

    【解决方案2】:

    我不喜欢Library XML,尤其是因为您需要创建和添加元素的行数。我专门使用新的网络库System.Xml.Linq。请参阅下面的代码:

    Imports System.Xml
    Imports System.Xml.Linq
    Module Module1
    
        Sub Main()
            Dim doc As New XDocument(New XElement("Test1", New XAttribute("Test2", "Test3")))
        End Sub
    
    End Module
    

    【讨论】:

      猜你喜欢
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多