You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VB.NET替换XML根标签:将ICICPayments替换为Payments

VB.NET 修改XML根节点:替换ICICPayments为Payments

针对你的需求,这里提供两种常见的VB.NET XML处理方案,你可以根据自己的习惯选择:

方法1:使用LINQ to XML(XDocument)

这种方式代码更简洁,是.NET中推荐的现代XML处理方式:

Imports System.Xml.Linq

' 原始XML内容
Dim originalXml 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>"

' 加载XML文档
Dim doc As XDocument = XDocument.Parse(originalXml)

' 创建新的根节点<Payments>
Dim newRoot As XElement = New XElement("Payments")

' 将原根节点下的所有<PaymentRecord>子节点转移到新根中
newRoot.Add(doc.Root.Elements())

' 构建包含XML声明的新文档
Dim newDoc As XDocument = New XDocument(
    New XDeclaration("1.0", "utf-8", Nothing),
    newRoot
)

' 输出结果(也可以用newDoc.Save("你的输出路径.xml")保存到文件)
Console.WriteLine(newDoc.ToString())

方法2:使用XmlDocument(传统XML处理)

如果你更习惯使用传统的XmlDocument类,也可以这样实现:

Imports System.Xml

' 原始XML内容
Dim originalXml 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 doc As New XmlDocument()
doc.LoadXml(originalXml)

' 创建新的根节点<Payments>
Dim newRoot As XmlElement = doc.CreateElement("Payments")

' 遍历原根节点的子节点,导入并添加到新根中
For Each node As XmlNode In doc.DocumentElement.ChildNodes
    newRoot.AppendChild(doc.ImportNode(node, True))
Next

' 替换原根节点
doc.ReplaceChild(newRoot, doc.DocumentElement)

' 添加XML声明
Dim declaration As XmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", Nothing)
doc.InsertBefore(declaration, doc.DocumentElement)

' 输出结果(也可以用doc.Save("你的输出路径.xml")保存到文件)
Console.WriteLine(doc.OuterXml)

最终输出结果

两种方法都会生成你需要的XML内容:

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

内容的提问来源于stack exchange,提问作者Rami Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:33:28