Question How to change parent nodes in xml

sterjo

Member
Joined
Aug 13, 2006
Messages
5
Programming Experience
Beginner
I have an xml file that looks like this
VB.NET:
<Operation ID="450">
    <Form ID="36" xsi:type="form-36">
      <AOP ID="1" Current="0" Previous="317200" xsi:type="aop-form-35" />
    </Form>
    <Form ID="36" xsi:type="form-36">
      <AOP ID="1" Current="0" Previous="317200" xsi:type="aop-form-36" />
      <AOP ID="9" Current="0" Previous="317200" xsi:type="aop-form-36" />
      <AOP ID="10" Current="0" Previous="0" xsi:type="aop-form-36" />
      <AOP ID="11" Current="0" Previous="0" xsi:type="aop-form-36" />
      <AOP ID="12" Current="0" Previous="0" xsi:type="aop-form-36" />
     </Form>
    <Form ID="36" xsi:type="form-36">
      <AOP ID="201" Current="0" Previous="546810" xsi:type="aop-form-37" />
      <AOP ID="202" Current="0" Previous="546810" xsi:type="aop-form-37" />
      <AOP ID="203" Current="0" Previous="0" xsi:type="aop-form-37" />
      </Form>
    <Form ID="36" xsi:type="form-36">
      <AOP ID="601" Current="0" Previous="0" xsi:type="aop-form-38" />
      <AOP ID="602" Current="0" Previous="0" xsi:type="aop-form-38" />
    </Form>
  </Operation>

The parent nodes appear to be same in the file which is wrong. How can I loop through the file with vb.net and change the parent nodes to:

VB.NET:
<Form ID="35" xsi:type="form-35">
<Form ID="36" xsi:type="form-36">
<Form ID="37" xsi:type="form-37">
<Form ID="38" xsi:type="form-38">

Thanks
Nick
 
This should work for ya:

    Public Sub FixFormNumbers(ByVal xmlPath As String)
        Dim xDoc = XDocument.Load(xmlPath)
        For Each f In (From x In xDoc...<Operation>...<Form>)
            Dim fNum = (From aop In f...<AOP>).First.@type.Split("-").Last
            f.@ID = fNum
            f.@type = "form-" & fNum
        Next
        xDoc.Save(xmlPath.Replace(".xml", "") & "-fixed.xml")
    End Sub


This looks at each <Form> tag that is a descendant of an <Operation> tag, takes the form ID from its first <AOP> tag, and replaces the ID and type properties of each form.
 
Last edited:
Herman said:
From x In xDoc...<Operation>...<Form>
From aop In f...<AOP>
Just notice ...<> is the descendants property, all selections here are child elements so it is sufficient and more correct to use .<> elements property. Specifically here xDoc...<Form> would select the same as xDoc.<Operation>.<Form>
 
Back
Top