我试图将一个通用树(无限子节点)关联到一个名为“pays.xml”的 XML 文件,如下所示:
<?xml version="1.0" encoding="iso-8859-1"?>
<country>
<name> </name>
<city> </city>
<region>
<name> </name>
<population> </population>
<city> Lille </city>
</region>
<region>
</region>
</country>
与此 XML 文件关联的树:
现在我想将这棵树转换为二叉树,我为此应用了一个算法:
使用通用树的根作为二叉树的根
确定根的第一个孩子。这是下一级通用树中最左边的节点
插入这个节点。父节点的子引用引用这个节点
继续查找每个父节点的第一个子节点,并将其插入到父节点下方,并带有父节点的子节点引用。
所以结果是:
所以我的问题是生成与二叉树相关联的 XML 文件,我想要的结果是:
<country>
<name>
<city>
<region>
<name>
<population>
<city>
</city>
</population>
</name>
<region></region>
</region>
</city>
</name>
</country>
我试图为此编写代码,但不幸的是,我得到了这个结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?><country><name/><city/><region><name/><population/><city/></region><region><name/><city/><city/></region></country>
这是我的代码:
public static Document Generer (Document doc, Node node,Node a )
{
NodeList nl = node.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
{
Element b = doc.createElement(n.getNodeName());
//System.out.print(b);
a.appendChild(b);
Generer (doc,n,b);
}
}
return doc;
}
public static void convert (Node node)
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element a=doc.createElement(node.getNodeName());
doc.appendChild(a);
doc=Generer (doc, node ,a);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(new File("C:\\file.xml"));
// Output to console for testing
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static Node GetNodeParent (String fichier1)
{
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(fichier1);
Element root = doc.getDocumentElement();
return root;
}catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node n1= GetNodeParent("pays.xml");
//System.out.println(n1);
convert(n1);
}