遍历XML文件中的所有节点以进行属性更改-vb.net

时间:2018-10-02 07:59:49

标签: xml vb.net

我有一个XML文件,我想在其中将名称为“ Product”的所有节点中的“ subtype”属性更改为其他值。但是以某种方式,我似乎在选择节点部分遇到了问题。

我的XML如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY: PLM XML SDK 7.0.4.411 -->
<PLMXML xmlns="http://www.plmxml.org/Schemas/PLMXMLSchema" language="en-us" 
 time="16:26:35" schemaVersion="6" author="Teamcenter 
 V10000.1.0.70_20161101.00 - infodba@PESYS(1470348095)" date="2018-09-25">
  <Product id="id35" name="78033031000" subType="Item" accessRefs="#id10" 
   productId="78033031000">
   <Description>78033031000</Description>
   <ApplicationRef application="Teamcenter" label="JfYtyiXp1pzuzD" 
   version="JfYtyiXp1pzuzD"></ApplicationRef>
  </Product>
<Product id="id66" name="0405222613" subType="Item" accessRefs="#id10" 
  productId="0405222613">
  <Description>0405222613</Description>
  <ApplicationRef application="Teamcenter" label="yCdhv99n1pzuzD" 
  version="yCdhv99n1pzuzD"></ApplicationRef>
</Product>
<Product id="id90" name="59033080000" subType="Item" accessRefs="#id10" 
  productId="59033080000">
  <Description>59033080000</Description>
  <ApplicationRef application="Teamcenter" label="0OShlqVN1pzuzD" 
  version="0OShlqVN1pzuzD"></ApplicationRef>
</Product>
</PLMXML>

所以我的直观尝试如下:

    'Load the XML file in XmlDocument.
    Dim doc As New XmlDocument()
    doc.Load("C:\export\79533500000.xml")
    'Fetch the specific Nodes by Name.
    Dim nodeList As XmlNodeList = doc.SelectNodes("/PLMXML/Product")
    'Loop through the selected Nodes.
    For Each node As XmlNode In nodeList



        'Fetch the Node and Attribute values.
        node("Product").SetAttribute("subType", "Product_Value12")

    Next
    doc.Save("C:\export\test_new.xml")
End Sub

这实际上没有任何作用,因此我尝试将 doc.SelectNodes(“ / PLMXML / Product”)更改为 doc.SelectNodes(“ *”) 会为“子类型”更改属性,但仅对第一个“产品”节点更改属性。

您能帮我告诉我我在做什么错吗?

感谢和问候 伯恩哈德

2 个答案:

答案 0 :(得分:0)

您缺少的是XML Reader!阅读/更改/保存。试试吧:

Dim doc As XmlDocument = New XmlDocument()
Dim xmlReader As XmlTextReader = New XmlTextReader(yourFilePath)
doc.Load(xmlReader)
Dim nodes As XmlNodeList = doc.SelectNodes("PLMXML/Product")

For Each node As XmlNode In nodes

    If node.Attributes("subType").Value.ToString() = "Item" Then
        node.Attributes("subType").Value = "New_Item"
    End If
Next

xmlReader.Close()
doc.Save(yourFilePath)

答案 1 :(得分:0)

如果删除此属性,它将起作用。

xmlns="http://www.plmxml.org/Schemas/PLMXMLSchema"

如果确实需要命名空间,则必须声明它

    Dim nsmanager As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmanager.AddNamespace("x", "http://www.plmxml.org/Schemas/PLMXMLSchema")

    Dim nodeList As XmlNodeList = doc.SelectNodes("//x:Product", nsmanager)

This answer可以提供更多有关此方面的详细信息。