0

I've got the following XML

<list name="Model">

  <list name="Info">
   <item name="ViewName">Page</item>
   <item name="DBField">Number</item>
   <item name="Type">int</item>
  </list>

  <list name="Info">
   <item name="ViewName">Page</item>
   <item name="DBField">Text</item>
   <item name="Type">String</item>
  </list>

  <list name="Codes">
  </list>

</list>

I want to add a New Child <list name="Info"> to <list name="Model">, the Child has to be inserted after the Last <list name="Info"> but before the <list name="Codes">part.

I've selected the last Info Node but can't figure out how to insert a node before the Codes node..

2
  • 1
    could you post your last workout Commented Aug 24, 2015 at 10:40
  • Set newNode = xmlDoc.createElement("list") newNode.setAttribute "name","Info" Set child1 = xmlDoc.createElement("item") Set child2 = xmlDoc.createElement("item") Set child3 = xmlDoc.createElement("item") child1.setAttribute "name","ViewName" child1.text = "Page" newNode.appendChild(child1) child2.setAttribute "name","DBField" child2.text = "Number2" newNode.appendChild(child2) child3.setAttribute "name","Type" child3.text = "int" newNode.appendChild(child3) Set oSingleNode = xmlDoc.selectSingleNode("(/list[@name='Model']/list[@name='Info'])[last()]") Commented Aug 24, 2015 at 10:49

1 Answer 1

1

Use .insertBefore as in:

Option Explicit

Dim oXML : Set oXML = CreateObject("Msxml2.DOMDocument")
oXML.async =  False
oXML.Load "..\data\32180204.xml"

If 0 = oXML.ParseError Then
   Dim sXPath  : sXPath      = "/list/list[@name='Codes']"
   Dim ndCodes : Set ndCodes = oXML.selectSingleNode(sXPath)
   If ndCodes Is Nothing Then
      WScript.Echo sXPath, "not found"
   Else
      Dim ndNew : Set ndNew = oXML.createElement("list")
      ndCodes.parentNode.insertBefore ndNew, ndCodes
      WScript.Echo oXML.xml
   End If
Else
   WScript.Echo oXML.ParseError.Reason
End If

output:

cscript 32180204.vbs
<list name="Model">
        <list name="Info">
                <item name="ViewName">Page</item>
                <item name="DBField">Number</item>
                <item name="Type">int</item>
        </list>
        <list name="Info">
                <item name="ViewName">Page</item>
                <item name="DBField">Text</item>
                <item name="Type">String</item>
        </list>
        <list/><list name="Codes">
        </list>
</list>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That's what i needed :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.