【问题标题】:VBA XML how can I get the Parent attribute from a child node?VBA XML 如何从子节点获取父属性?
【发布时间】:2014-09-18 19:00:15
【问题描述】:

我有一个搜索屏幕,您可以在其中选择不同的选项(作为子节点的项目)。点击搜索后,我想浏览一个 XML 文档并检索父节点属性。例如:

<?xml version="1.0" encoding="UTF-8"?>
<brands>
  <BrandA Name="A Brand">
     <Color>Black</Color>
     <Thickness>1"</Thickness>
     <Texture>Smooth</Texture>
  </BrandA>
  <BrandB Name="B Brand">
     <Color>Red</Color>
     <Thickness>2"</Thickness>
     <Texture>Smooth</Texture>
  </BrandB>
  <BrandC Name="C Brand">
     <Color>Green</Color>
     <Thickness>3"</Thickness>
     <Texture>Rough</Texture>
  </BrandC>
</brands> 

如果有人从“粗糙”纹理中搜索,我如何获得 BrandC Name 的父节点?

VBA 代码:

For Each T In objDom.getElementsByTagName("Texture") 

    MsgBox T.Text 'For testing to see what it returns (all 3 textures).

If ComboBox3.Value = T.Text Then
    'For testing: This returns all matching textures that was selected.
    MsgBox T.ParentNode.Text 
End If

所以这会返回所有品牌名称、颜色、厚度、质地。我只需要品牌名称即“C Brand”。

【问题讨论】:

  • 这将有助于显示您的“搜索”代码。 parentNode 可能是您想要的 - 然后是 getAttribute()
  • @Tim Williams 我试过 parentNode 但这会返回该节点下的所有内容。 IE 品牌名称、颜色、厚度和质地。
  • Tim 想说的是:显示您的 VBA 代码。在你展示你已经尝试过的东西之前,你说你尝试过什么并不重要。

标签: xml vba nodes


【解决方案1】:

而不是T.ParentNode.Text 我相信你会想要T.ParentNode.Attributes.getNamedItem("Name").Text

【讨论】:

  • 成功了。现在,如果我在那个之上有另一个父节点怎么办。如何获得二级父节点?
  • 我想通了,对于每个级别我都必须添加一个额外的 ParentNode,所以 ParenNode.ParentNode.Attributes.getNamedItem("AnotherName").Text
  • 在 XML DOM(以及带有 HTML 库的 HTML DOM)中移动实际上很有趣。例如,您可以使用 Node.Parent.Parent.NextSibling.Child.Child.text 浏览它,这会将您踢到节点的祖父母,然后到它的兄弟姐妹(节点的姑姑/叔叔),然后到他们的祖父孩子和拉他们的文字。诀窍是使用.getElementsByTagName 或其他元素搜索功能尽可能接近,然后使用关系缩小您想要的范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多