将XML标记替换为另一个标记并使用VB.net添加新标记

时间:2018-05-28 09:12:17

标签: xml vb.net

下面是我输入的xml文件数据:

    <ICICPayments xmlns="http://elite.com/schemas/transaction/object/read/ACHPay">
  <PaymentRecord>    
    <PaymentDetails>      
      <PaymentAmount>148.39</PaymentAmount>
      <Date>2017-11-23</Date>      
    </PaymentDetails>    
  </PaymentRecord>
  <PaymentRecord>    
    <PaymentDetails>
      <PaymentAmount>990.44</PaymentAmount>
      <Date>2017-11-23</Date>      
    </PaymentDetails>    
  </PaymentRecord>  
</ICICPayments>

Excepted Out put:

<?xml version="1.0" encoding="utf-8"?>
<Payments>
  <PaymentRecord>
    <PaymentDetails>
      <PaymentAmount>148.39</PaymentAmount>
      <Date>2017-11-23</Date>
    </PaymentDetails>
  </PaymentRecord>
  <PaymentRecord>
    <PaymentDetails>
      <PaymentAmount>990.44</PaymentAmount>
      <Date>2017-11-23</Date>
    </PaymentDetails>
  </PaymentRecord>
</Payments>
  • 使用VB.net我们需要从xml中删除'ICICPayments'标记 档案数据。需要将新标记添加为“付款”

2 个答案:

答案 0 :(得分:0)

您可以使用以下解决方案:

Dim xmlContent As String = "<ICICPayments xmlns=""http://elite.com/schemas/transaction/object/read/ACHPay"">" & _
    "<PaymentRecord>" & _
    "<PaymentDetails>" & _
    "<PaymentAmount>148.39</PaymentAmount>" & _
    "<Date>2017-11-23</Date>" & _
    "</PaymentDetails>" & _
    "</PaymentRecord>" & _
    "<PaymentRecord>" & _
    "<PaymentDetails>" & _
    "<PaymentAmount>990.44</PaymentAmount>" & _
    "<Date>2017-11-23</Date>" & _
    "</PaymentDetails>" & _
    "</PaymentRecord>" & _
    "</ICICPayments>"
Dim xmlDoc As New XmlDocument()
xmlDoc.LoadXml(xmlContent)

Dim xmlNodes As XmlNodeList = xmlDoc.GetElementsByTagName("ICICPayments")

If xmlNodes.Count = 1 Then

    'get the innerXML of the "ICICPayments" element.
    Dim innerXML As String = xmlNodes(0).InnerXml

    'remove the whole XML content.
    xmlDoc.RemoveAll()

    'create and add the XML declaration.
    xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""))

    'create the new XML element "Payments"
    Dim elementPayments As Xml.XmlElement = xmlDoc.CreateElement("Payments")

    'insert the innerXML of the ICICPayments element.
    elementPayments.InnerXml = innerXML

    'add the new XML element "Payments" to the XML document.
    xmlDoc.AppendChild(elementPayments)
End If

Debug.Print(xmlDoc.InnerXML) 'new xml content

答案 1 :(得分:0)

或者你可以这样做:

    Dim OrgXml As New XmlDocument
    OrgXml.Load("YourXmlfile.xml")


    Dim newDocEle As XmlElement = OrgXml.CreateElement("Payments")

    While OrgXml.DocumentElement.HasChildNodes
        newDocEle.AppendChild(OrgXml.DocumentElement.ChildNodes(0))
    End While

    OrgXml.RemoveChild(OrgXml.DocumentElement)
    OrgXml.AppendChild(newDocEle)

    OrgXml.Save("YourNewXmlFile.xml")