VB.net XML按标记名称删除每个第二个元素

时间:2017-08-30 18:02:05

标签: xml vb.net

我正在使用以下XML示例:

<order>
    <name></name>
    <etc></etc>
    <etc></etc>
    <components>
        <component>
            <sub></sub>
        </component>
        <component>
            <sub></sub>
        </component>
        <component>
            <sub></sub>
        </component>
        <component>
            <sub></sub>
        </component>
    </components>
</order>

我正在尝试在vb.net中选择并删除每秒<component>sub

以下是我到目前为止的内容:

'make xmldocument object to hold xml string'
Dim XMLDoc As New XMLDocument()
XMLDoc.LoadXML(strXMLContent)
'get all elements named component'
Dim componentList As XmlNodeList = XMLDoc.GetElementsByTagName("Component")
Dim c As Integer
Dim i As Integer = 1
'for every component element add i to itself to only get seconds'
'and if on a second element, remove it and all sub elements inside it'
For c = 0 To componentList.Count - 1
    i += i
    If i > 2 Then
        componentList(c).ParentNode.RemoveChild(componentList(c))
    End If
Next c
'output to a string to see results'
x &= XMLDoc.DocumentElement.OuterXml

我遇到的问题是,当我在调用实际Object reference not set to an instance of an object的行上运行时,我会收到“RemoveChild()”。

2 个答案:

答案 0 :(得分:0)

试试这个:

Private Function GetRidOfEveryOtherComponent(ByVal strXML As String) As String
    'make xmldocument object to hold xml string'
    Dim XMLDoc As New XmlDocument()
    XMLDoc.LoadXml(strXML)
    'get every other component item
    Dim componentList As XmlNodeList = XMLDoc.SelectNodes("order/components/component[position() mod 2 = 1]")
    For c As Integer = 0 To componentList.Count - 1
        componentList(c).ParentNode.RemoveChild(componentList(c))
    Next c
    'output to a string to see results'
    Return XMLDoc.DocumentElement.OuterXml
End Function

这个很酷的mod功能是保罗的礼貌,在这里:Selecting every other node uing XPATH

答案 1 :(得分:0)

我的问题是两件事,我是如何添加我的i整数,以及if语句结构,当它合并时,使得componentList(c)我删除了,真的是null。以下是我的工作修复。

'make xmldocument object to hold xml string'
 Dim XMLDoc As New XMLDocument()
 XMLDoc.LoadXML(strXMLContent)
'get all elements named component'
 Dim componentList As XmlNodeList = XMLDoc.GetElementsByTagName("Component")
 Dim c As Integer
 Dim i As Integer = 0
'for every "Component" element add 1 to i - remove every second by checking if i is modular'
 For c = 0 To componentList.Count - 1
     i += 1
     If Not i Mod 2 Then
         componentList(c).ParentNode.RemoveChild(componentList(c))
     End If
 Next c
'output to a string to see results'
 x &= XMLDoc.DocumentElement.OuterXml