遍历XML,在指定位置插入节点

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class TestXML
{

 static List<Boolean> result1 = new ArrayList<Boolean>();

 /**
  * 这个方法获取给定Node下的Text节点,如果不存在Text节点则返回null。 注意:是直接子节点,相差2层或2层以上不会被考虑。
  *
  * @param node
  *            a Node 一个Node。
  * @return a Text 如果给定节点存在Text子节点,则返回第一个访问到的Text子节点,如果不存在则返回null。
  */
 public static Text getTextNode(Node node)
 {
  if (node == null)
  {
   return null;
  }
  if (node.hasChildNodes())
  {
   NodeList list = node.getChildNodes();
   for (int i = 0; i < list.getLength(); i++)
   {
    if (list.item(i).getNodeType() == Node.TEXT_NODE)
    {
     return (Text) list.item(i);
    }
   }
  }
  return null;
 }

 public static String getNodeValue(Node node)
 {
  if (node == null)
  {
   return null;
  }

  Text text = getTextNode(node);

  if (text != null)
  {
   return text.getNodeValue();
  }

  return null;
 }

 public static boolean checkExist(Node root, String nodeName)
 {
  // 检查XML中是否存在
  if (root.hasChildNodes())
  {
   List<Boolean> r1 = new ArrayList<Boolean>();
   NodeList nodeList = root.getChildNodes();
   for (int i = 0; i < nodeList.getLength(); i++)
   {
    boolean ret = checkExist(nodeList.item(i), nodeName);
    if (ret)
    {
     return true;
    }
   }
   return false;
  }
  else
  {
   if (root.getTextContent().equals(nodeName))
   {
    return true;
   }
   else
   {
    return false;
   }
  }
 }

 /**
  * 1、获取原XML dom元素根节点 2、保存当前循环节点的上节点名 3、
  */
 public static void main(String[] args)
 {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  List<String> nodeNameList1 = new ArrayList<String>();
  nodeNameList1.add("M1");
  nodeNameList1.add("M2");
  nodeNameList1.add("M3");
  nodeNameList1.add("M4");
  nodeNameList1.add("M5");
  try
  {
   DocumentBuilder db = dbf.newDocumentBuilder();
   // 读入xml文档
   String path = "D:\\test.xml";
   Document document;
   document = db.parse(new File(path));
   Node root = document.getDocumentElement();

   for (int c = 0; c < nodeNameList1.size(); c++)
   {
    String currNodeName = nodeNameList1.get(c);
    System.out.println("currNodeName:" + currNodeName);
    boolean isExist = checkExist(root, currNodeName);
    System.out.println(isExist);
    // 如果不存在需要新增一节点
    if (!isExist)
    {
     // 获取所有desc节点,循环比较。
     NodeList nodeList = document.getElementsByTagName("desc");
     for (int i = 0; i < nodeList.getLength(); i++)
     {
      Node currNode = nodeList.item(i);
      String nodeName = currNode.getNodeName();
      String nodeValue = currNode.getTextContent();
      System.out.println("nodeName:" + nodeName);
      System.out.println("nodeValue:" + nodeValue);
      System.out.println("nodeNameList1.get(c - 1):" + nodeNameList1.get(c - 1));
      // 取前一节点的元素
      if (nodeValue.equals(nodeNameList1.get(c - 1)))
      {
       Element newnode0 = (Element) document.createElement("bill_1");
       Element newnode1 = (Element) document.createElement("desc");
       newnode1.appendChild(document.createTextNode("xxxx Fee"));
       Element newnode2 = (Element) document.createElement("amount");
       newnode2.appendChild(document.createTextNode("0.00"));
       newnode0.appendChild(newnode1);
       newnode0.appendChild(newnode2);
       root.insertBefore(newnode0, currNode);
       break;
      }
     }
    }
   }

   // 利用transformer对象将修改后的文档重新输出
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   transformer = tFactory.newTransformer();

   DOMSource source = new DOMSource(document);
   // 将xml文档保存
   StreamResult result = new StreamResult(new java.io.File("D:\\test.xml"));
   transformer.transform(source, result);
  }
  catch (TransformerConfigurationException e)
  {
   e.printStackTrace();
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }

 }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C#中操作XML文档,可以使用`System.Xml.Linq`命名空间提供的类库来进行XML的读取、修改和写入等操作。以下是关于如何在XML文档插入同级根节点和子节点的基本步骤: ### 插入同级根节点 假设你有一个XML字符串或者已经加载了XML文件到Linq to XML的DOM树中。为了插入一个新的同级根节点,你可以通过遍历当前根元素的所有子元素,并在适当的位置创建新的元素。 #### 示例代码: ```csharp using System; using System.IO; using System.Xml.Linq; class Program { static void Main() { // 创建原始的XML字符串 string xmlStr = "<root>\n" + " <childA>Value A</childA>\n" + " <childB>Value B</childB>\n" + "</root>"; XDocument doc = XDocument.Parse(xmlStr); // 获取所有孩子节点 XElement root = (XElement)doc.Root!; IEnumerable<XElement> children = root.Elements(); // 计算孩子节点的数量 int childCount = children.Count(); // 创建新元素并插入指定位置 XElement newChild = new XElement("newChild", "New Value"); doc.Root.Insert(childCount, newChild); // 写出修改后的XML字符串 string updatedXmlStr = doc.ToString(); Console.WriteLine(updatedXmlStr); } } ``` ### 插入节点 插入节点相对简单,只需要使用 `Add()` 方法将新元素添加到所需的位置即可。这里同样假设我们已经有了一个XML文档和其结构的引用。 #### 示例代码: ```csharp using System; using System.IO; using System.Xml.Linq; class Program { static void Main() { // 使用相同的XML字符串作为示例 string xmlStr = "<root>\n" + " <childA>Value A</childA>\n" + " <childB>Value B</childB>\n" + "</root>"; XDocument doc = XDocument.Parse(xmlStr); // 找到要插入节点的元素位置,这里是找到名为"childA"的第一个元素之后 XElement parentElement = doc.Descendants("childA").First().Parent!; XElement childToInsert = new XElement("newChild", "Inserted Value"); // 将新元素插入到找到的元素之后 parentElement.AddAfterSelf(childToInsert); // 写出修改后的XML字符串 string updatedXmlStr = doc.ToString(); Console.WriteLine(updatedXmlStr); } } ``` ### 相关问题: 1. 在XML文档中如何查找特定元素的子元素? 2. 怎样从已解析的XML文档中删除某个节点? 3. C#中的LINQ to XML是否支持动态修改XML结构,例如改变属性值或者删除某些元素? --- 注意:以上代码示例需要正确处理异常情况,如XML解析错误、节点不存在等问题,在实际应用中应加入适当的错误检查机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值