【问题标题】:Straight access to xml attribute value with xml inside使用里面的 xml 直接访问 xml 属性值
【发布时间】:2014-04-01 23:05:28
【问题描述】:

我下面有xml:

<Team>
<Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/>
</Team>

我想找到一种方法来直接加载属性 LastFight,而无需创建大量 xmldocuments。这是我使用的代码:

Dim storagexml As New XmlDocument
storagexml.LoadXml(<Team><Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/></Team>)
Dim tempnodelist As XmlNodeList = storagexml.SelectNodes("Team/Member")
For Each tempnode As XmlNode In tempnodelist
If tempnode.Attributes("Name") IsNot Nothing Then
Dim tempdoc As New XmlDocument
tempdoc.LoadXml(tempnode.Attributes("Info").Value)
Dim tempsel As XmlNode = tempdoc.SelectSingleNode("Info")
If Not tempsel.Attributes("LastFight").Value.Trim() = "" Then
RichTextBox1.AppendText(tempnode.Attributes("Name").Value & " " & tempsel.Attributes("LastFight").Value & vbCrLf)
End If

【问题讨论】:

  • 目前我脑海中浮现的最大问题是:为什么在 XML 文件的属性中包含 HTML 编码的 XML?这可能是您可以更改的东西,而不是尝试将属性作为字符串提取,解码 HTML 编码的字符并将其加载到 XML 文档中?
  • 因为会有一些文本在里面包含&符号。为了防止出现任何错误,决定照原样放。
  • 因此,您对可能包含与号的文本进行编码,仅此而已。对整个 XML 文档进行编码并将其放入另一个 XML 文档的文本属性中,类似于使用大锤杀死蚂蚁。

标签: .net xml vb.net


【解决方案1】:

Info 属性的值是另一个 XML 字符串,据我所知,您无法避免将其加载到另一个 XML 抽象对象(例如 XmlDocument)。

无论如何,您都可以使用 LINQ-to-XML 来简化代码。例如使用 XElement 和 VB.NET 特定功能来访问部分 XML 内联:

Dim xml = <Team>
              <Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/>
          </Team>

'notice how to access child element and attribute inline :
'
Dim info = XElement.Parse(xml.<Member>.@Info)
Dim lastFight As String = info.@LastFight
Console.WriteLine(lastFight)

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    相关资源
    最近更新 更多