簡體   English   中英

如何使用 vb.net 在特定位置創建一個 xml 元素?

[英]How to create an xml element in a specific position using vb.net?

我試圖在另一個元素之后在特定位置創建一個 xml 元素,但該元素被添加到另一個元素內並添加了 xmlns 部分。 我也不想要'xmlns'。 我需要補充的是:

我需要添加元素的地方

我試過的是這樣的:

        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)

發生的事情是這樣的:

 <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>

根據您的圖片,這似乎是您想要做的(Basdandosi nella tua immagine sembra sia questo quello che stai cercando):

    refChild.AppendChild(newChild) 

但。 根據您的問題,您似乎想這樣做(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

使用 Xml Linq。 找到patientRole,然后將新的id添加到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM