0

I am trying to create an xml element after another element, in a specific position but the element is added inside another element and has an xmlns part added. I dont want 'xmlns' there also. What I need to add is this:

Where I need the element to be added

What I have tried is this:

        Dim cda As New XmlDocument
        Dim refChild As XmlNode = cda.SelectSingleNode("//cr:recordTarget/cr:patientRole/cr:id", NS)
        Dim newChild As XmlElement = cda.CreateElement("id")
        newChild.SetAttribute("root", "2.16.840.1.113883.2.9.4.3.1")
        newChild.SetAttribute("extension", "DLCVCN48S05L049B")
        refChild.InsertBefore(newChild, refChild.FirstChild)

What happens is this:

 <id root="2.16.840.1.113883.2.9.4.3.2" extension="PTRFMN46E69D171X" 
 assigningAuthorityName="Ministero Economia e Finanze">
 <id root="2.16.840.1.113883.2.9.4.3.1" extension="DLCVCN48S05L049B" xmlns="" />
  </id>
Nina
  • 97
  • 1
  • 9

2 Answers2

0

Based in your pic seems is this what you want to do (Basdandosi nella tua immagine sembra sia questo quello che stai cercando):

    refChild.AppendChild(newChild) 

But. Based on your question seems you want to do this (Ma basandosi nella domanda):

    Dim newChild As Xml.XmlElement = cda.CreateElement("id", cda.DocumentElement.NamespaceURI)
    newChild.SetAttribute("root", "2.16.840.1.113883.2.9.4.3.1")
    newChild.SetAttribute("extension", "DLCVCN48S05L049B")
    newChild.InnerText = " "


    If refChild.ParentNode IsNot Nothing Then
        refChild.ParentNode.InsertAfter(newChild, refChild)
    End If
G3nt_M3caj
  • 2,497
  • 1
  • 14
  • 16
  • Thank you! Adding xml element in a specific position works good! xmlns displays again, trying to find another choice for that. :) – Nina Mar 25 '20 at 08:44
  • Ti ho aggiornato la risposta (fai attenzione alla creazione del nodo) per quanto riguarda l’attributo “xmlns”. Fammi sapere. Good luck ;) – G3nt_M3caj Mar 25 '20 at 09:04
0

Use Xml Linq. Find patientRole and then add new id to patientRole :

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)
        Dim patientRole = doc.Descendants().Where(Function(x) x.Name.LocalName = "patientRole").FirstOrDefault()

        Dim newPatient As XElement = New XElement("id", New Object() {New XAttribute("root", "2.16.840.1.113883.2.9.4.3.2"), New XAttribute("extension", "PTRFMN46E69D171X"), New XAttribute("assigningAuthorityName", "Ministero Economia e Finanze")})
        patientRole.Add(newPatient)
    End Sub

End Module
jdweng
  • 33,250
  • 2
  • 15
  • 20