连接元素节点由相同的状态名称组成一个元素节点

Posted

技术标签:

【中文标题】连接元素节点由相同的状态名称组成一个元素节点【英文标题】:Concatenate Elements nodes consist of same state name into one element node 【发布时间】:2021-08-26 05:55:10 【问题描述】:

输入 XML 文件

<ContactD>
  <addr>
    <name>jack</name>
    <street>south street</street>
    <state>Tamilnadu</state>
    <country>India</country>
    <pin>621716</pin>
  </addr>
  <addr>
    <name>Benjamin</name>
    <street>north street</street>
    <state>Tamilnadu</state>
    <country>India</country>
    <pin>621706</pin>
  </addr>
  <addr>
    <name>Ryan</name>
    <street>East street</street>
    <state>Kerala</state>
    <country>India</country>
    <pin>67322</pin>
  </addr>
</ContactD>

输出应该是这样的:

<ContactD>
  <addr>
    <name>jack,Benjamin</name>
    <street>south street,north street</street>
    <state>Tamilnadu</state>
    <country>India</country>
    <pin>621716,621706</pin>
  </addr>
   <addr>
    <name>Ryan</name>
    <street>East street</street>
    <state>Kerala</state>
    <country>India</country>
    <pin>67322</pin>
  </addr>
</ContactD>

我尝试使用 Java 代码我尝试匹配 state 元素之后我不知道如何将这两者连接成一个

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//import com.sun.org.apache.xml.internal.security.utils.XPathFactory;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class Jparser 

  private static final String FILENAME = "books.xml";

  public static void main(String[] args) 

      // Instantiate the Factory
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      try 

          // optional, but recommended
          // process XML securely, avoid attacks like XML External Entities (XXE)
          dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

          // parse XML file
          DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(new File(FILENAME));

          // optional, but recommended
          // http://***.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
          doc.getDocumentElement().normalize();

          System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
          System.out.println("------");

          // get <staff>
          NodeList list = doc.getElementsByTagName("addr");
          String[] hell= new String[3];

          for (int temp = 0; temp < list.getLength(); temp++) 

              Node node = list.item(temp);

              if (node.getNodeType() == Node.ELEMENT_NODE) 

                  Element element = (Element) node;

               
                  String name = element.getElementsByTagName("name").item(0).getTextContent();
                  String street = element.getElementsByTagName("street").item(0).getTextContent();
                  hell[temp]= element.getElementsByTagName("state").item(0).getTextContent();
                  String country = element.getElementsByTagName("country").item(0).getTextContent();
                  String pin = element.getElementsByTagName("pin").item(0).getTextContent();

             
       

                  System.out.println("Current Element :" + node.getNodeName());
                  System.out.println("name : " + name);
                  System.out.println("street : " + street);
                  System.out.println("state : " + hell[temp]);
                  System.out.println("country : " + country);
                  System.out.printf("pin :"+ pin);
              
          
          for (int t = 0; t < list.getLength()-1; t++) 
              if(hell[t].equals(hell[t+1])) 
                  /////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
                   System.out.println("same");
              
              


       catch (ParserConfigurationException | SAXException | IOException e) 
          e.printStackTrace();
      

  


当我尝试将我识别为相同的两个元素节点联系为一个时,我卡住了...我完成了匹配这些状态节点...需要连接帮助!

【问题讨论】:

JQuery 和 html 是从哪里来的?另请注意,您在此处包含的任何内容都不是可运行的 javascript sn-p - 我现在会相应地编辑问题,但以后请多加注意。 tnx 我以后会更小心的 【参考方案1】:

输入

<ContactD>
<addr>
<name>jack</name>
<street>south street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716</pin>
</addr>
<addr>
<name>Benjamin</name>
<street>north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
<addr>
<name>yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>

预期输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><ContactD>
<addr>
<name>jack,Benjamin</name>
<street>south street,north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716,621706</pin>
</addr>

<addr>
<name>Ryan,yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>

</ContactD>

这个连接的Javacode如下:(抱歉太多冗余的cmets和不均匀的代码)

         import java.io.File;
         //  j  a v  a  2  s .co  m
         import javax.xml.parsers.DocumentBuilder;
          import javax.xml.parsers.DocumentBuilderFactory;
           import javax.xml.transform.Result;
         import javax.xml.transform.Source;
          import javax.xml.transform.Transformer;
         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.xml.sax.SAXException;
  
           //import com.sun.org.apache.xml.internal.security.utils.XPathFactory;

           import javax.xml.XMLConstants;
            import javax.xml.parsers.ParserConfigurationException;
            import java.util.ArrayList;
            import java.io.IOException;

             public class Jparser 

               private static final String FILENAME = "books.xml";
            private static void toString(Document newDoc) throws Exception
              TransformerFactory tranFactory = TransformerFactory.newInstance();
               Transformer aTransformer = tranFactory.newTransformer();
               Source src = new DOMSource(newDoc);
             Result dest = new StreamResult(new File("books.xml"));
              aTransformer.transform(src, dest);
             


          public static void main(String[] args) throws Exception 


           // Instantiate the Factory
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

         try 

      // optional, but recommended
      // process XML securely, avoid attacks like XML External Entities (XXE)
      dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

      // parse XML file
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(new File(FILENAME));

      // optional, but recommended
      // http://***.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
      doc.getDocumentElement().normalize();

      System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
      System.out.println("------");

      // get <staff>
      NodeList list = doc.getElementsByTagName("addr");
      //String[] hell= new String[10];
      ArrayList<String> hell = new ArrayList<String>();
      ArrayList<Element> Ements = new ArrayList<Element>();

      for (int temp = 0; temp < list.getLength(); temp++) 

          Node node = list.item(temp);

          if (node.getNodeType() == Node.ELEMENT_NODE) 

              Element element = (Element) node;
              Ements.add(element);
              

           
              String name = element.getElementsByTagName("name").item(0).getTextContent();
              String street = element.getElementsByTagName("street").item(0).getTextContent();
              hell.add(element.getElementsByTagName("state").item(0).getTextContent());
              String country = element.getElementsByTagName("country").item(0).getTextContent();
              String pin = element.getElementsByTagName("pin").item(0).getTextContent();

         
   

              System.out.println("Current Element :" + node.getNodeName());
              System.out.println("name : " + name);
              System.out.println("street : " + street);
              System.out.println("state : " + hell.get(temp));
              System.out.println("country : " + country);
              System.out.printf("pin :"+ pin);
          
      
      
      System.out.println("The size of the ArrayList is: " + Ements.size());
     // System.out.println(Ements.get(0).name);
      for (int t = 0; t < Ements.size()-1; t++) 
         // for(int s=1;s<Ements.size()-1;s++) 

          //for(int d=1; d<list.getLength()-1;d++) 
          if(hell.get(t).equals(hell.get(t+1))) 
              /////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
             // int z=t;
              String[] he= "name","street","state","country","pin";
              for(int a=0; a<he.length; a++) 
                  //System.out.printf(Ements.get[a]);
                 String zz0=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent();
                 String zz1=Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
                 if(!zz0.equals(zz1))
                     Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz0+","+zz1);
                 
            //String zz=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent()+","+Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
     
                 // Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz);
                 // System.out.println(Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent());   
              
              doc.getDocumentElement().removeChild(Ements.get(t+1));
              Ements.remove(t+1);
              hell.remove(t+1);
              System.out.println(Ements.size());
              
              
               
          
      
      
      System.out.println(Ements.size());
     // DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
     // DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

      //Document newDoc = domBuilder.newDocument();
     //Element rootElement = newDoc.createElement("parent");
     // NodeList toremove=doc.getDocumentElement().getChildNodes();
      //for(int i=0;i<toremove.getLength();i++) 
        //  doc.getDocumentElement().removeChild(toremove.item(i));
          
      //
     
      //doc.getDocumentElement().appendChild(Ements.get(0));
      //doc.getDocumentElement().appendChild(Ements.get(1));
      
      
      toString(doc);  
   
             
                  
            
               
         
          
      


   catch (ParserConfigurationException | SAXException | IOException e) 
      e.printStackTrace();
  

【讨论】:

以上是关于连接元素节点由相同的状态名称组成一个元素节点的主要内容,如果未能解决你的问题,请参考以下文章

0050数据结构之并查集

xml 中具有相同元素名称的下一个节点

数据结构与算法之深入解析“冗余连接II”的求解思路与算法示例

如何获取具有相同名称的元素并根据 XSLT 中的子节点值对它们进行排序

LeetCode——冗余连接

Leetcode 684.冗余连接