将子节点从XML文件拆分为自己的XML文件 [英] Splitting child node from XML file into their own XML files

查看:659
本文介绍了将子节点从XML文件拆分为自己的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件(在左边),我想创建多个文件(右边):

  < ParentNode> file1:
<子节点> < ParentNode>
< node>< / node> < ChildNode>
< / childNode> <节点>< /节点>
<子节点> < / childNode>
< node>< / node> < / ParentNode>
< / childNode> file2:
< ChildNode> < ParentNode>
< node>< / node> < ChildNode>
< / childNode> <节点>< /节点>
< / ParentNode> < / childNode>
< / ParentNode>

我正在尝试从原始XML文件中获取第一个子节点,并将其添加到新的但是我不得不在更换节点时收到错误。



我想做一些类似于以下的事情。

  DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); 
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
文档newDocument;

Node firstChild = document.getFirstChild();
NodeList childNodes = firstChild.getChildNodes();

元素parentNode; (int i = 1; i< childNodes.getLength(); i ++){
newDocument = docBuilder.newDocument();

parentNode = newDocument.createElement(ParentNode);
newDocument.appendChild(parentNode);
newDocument.getFirstChild()。appendChild(childNodes.item(i));
}

但是我收到错误

  org.w3c.dom.DOMException:WRONG_DOCUMENT_ERR:一个节点用于与创建它不同的文档中。 

任何帮助指向正确方向赞赏!

解决方案

从Java文档中,



使用 cloneNode 方法



< blockquote>

摘要:

  public Node cloneNode(boolean deep)

返回此节点的副本,
ie作为节点的通用副本
构造函数。重复的
节点没有父节点; (parentNode是
null。)。克隆元素复制所有
属性及其值,包括
由$ x
生成的代表默认属性的值,但$
这个方法不会复制
包含的任何文本,除非它是一个深克隆,
,因为文本包含在一个孩子
文本节点。直接克隆属性
,而不是克隆为
元素克隆操作的一部分,
返回指定的属性(
指定为true)。克隆任何其他
类型的节点只返回
这个节点的副本。



请注意,克隆不可变子树
导致可变副本,但是EntityReference克隆

子元素是只读的。另外,指定
未指定的Attr节点的克隆。
而且,克隆Document,DocumentType,
实体和符号节点是
实现依赖。


编辑:

  import java.io. *; 
import javax.xml.parsers。*;
import org.w3c.dom。*;
import org.xml.sax。*;
import javax.xml.transform。*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class Test {
static public void main(String [] arg)throws Exception {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
文档doc = builder.parse(foo.xml);

TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();


NodeList list = doc.getFirstChild()。getChildNodes(); (int i = 0; i< list.getLength(); i ++){
Node element = list.item(i).cloneNode(true);



if(element.hasChildNodes()){
源src = new DOMSource(element);
FileOutputStream fs = new FileOutputStream(k+ i +.xml);
结果dest = new StreamResult(fs);
aTransformer.transform(src,dest);
fs.close();
}
}

}
}


I have an XML file (on the left) and I want to create multiple files (on the right):

<ParentNode>                                  file1:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
    <ChildNode>                                   </childNode>
        <node></node>                         </ParentNode>
    </childNode>                              file2:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
</ParentNode>                                      </childNode>
                                              </ParentNode>

I am trying to take the first child node from the original XML file and add it to a new one but I keep getting errors around replacing nodes.

I want to do something like the following

 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
 Document newDocument;

 Node firstChild = document.getFirstChild();
 NodeList childNodes = firstChild.getChildNodes();

 Element parentNode;
 for (int i = 1; i < childNodes.getLength(); i++ ) {
     newDocument = docBuilder.newDocument();
     parentNode = newDocument.createElement("ParentNode");
     newDocument.appendChild(parentNode);
     newDocument.getFirstChild().appendChild(childNodes.item(i));
 }

but I get an error

org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.

any help pointing in the right direction appreciated!

解决方案

From Java documentation,

Use cloneNode method.

SUMMARY:

public Node cloneNode(boolean deep)

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent; ( parentNode is null.).

Cloning an Element copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node. Cloning an Attribute directly, as opposed to be cloned as part of an Element cloning operation, returns a specified attribute ( specified is true). Cloning any other type of node simply returns a copy of this node.

Note that cloning an immutable subtree results in a mutable copy, but the children of an EntityReference clone are readonly . In addition, clones of unspecified Attr nodes are specified. And, cloning Document, DocumentType, Entity, and Notation nodes is implementation dependent.

EDIT :

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class Test{
 static public void main(String[] arg) throws Exception{

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 Document doc = builder.parse("foo.xml");

 TransformerFactory tranFactory = TransformerFactory.newInstance(); 
 Transformer aTransformer = tranFactory.newTransformer(); 


 NodeList list = doc.getFirstChild().getChildNodes();

 for (int i=0; i<list.getLength(); i++){
    Node element = list.item(i).cloneNode(true);

 if(element.hasChildNodes()){
   Source src = new DOMSource(element); 
   FileOutputStream fs=new FileOutputStream("k" + i + ".xml");
   Result dest = new StreamResult(fs);
   aTransformer.transform(src, dest);
   fs.close();
   }
   }

  }
}

这篇关于将子节点从XML文件拆分为自己的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆