gpt4 book ai didi

java - 如何使用java制作动态xml

转载 作者:行者123 更新时间:2023-12-01 15:58:46 24 4
gpt4 key购买 nike

我有一个固定的 XML 模板,节点可能会根据数据增加。如果我有一个固定的模板。当提供父节点名称时,如何迭代所有子节点?我可以根据 xpath 制作 XML 吗?

我有以下代码:-

Map map = hm(); 
Set set = map.entrySet();
// Get an iterator
Iterator it = set.iterator();
// Display elements
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
if (check) {
xpath_String+= "|"+me.getKey();
}else {
xpath_String+= me.getKey();
check = true;
}
}

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
//xml file name acts as template
Document doc = builder.parse("template.xml");


XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(xpath_String);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Total number of tokens: "+nodes.getLength());
//for (int i = 0; i < nodes.getLength(); i++) {

int i=0;

StringTokenizer st = new StringTokenizer(xpath_String,"|");

while (st.hasMoreElements()) {
String val = (String) st.nextElement();
if(hm().containsKey(val)){
System.out.println("Node value is: "+nodes.item(i).getNodeName());
nodes.item(i).setTextContent(hm().get(val).toString());
i++;
}
}
//}

//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
// generating the output file name
StreamResult finalResult = new StreamResult(new File("newfxml.xml"));
transformer.transform(source, finalResult);

//making a string for the dom
StringWriter writer = new StringWriter();
StreamResult stResult = new StreamResult(writer);
transformer.transform(source, stResult);

这里我有一个固定的模板和一张 map 。从 map 中我得到了 xpath 及其相应的值。只有在模板 xml 中的节点不再重复之前,这种情况才有效。所以我想知道当我获得可重复组件时是否有任何方法可以迭代整个 xml 节点 block 。有这样的解决办法吗?或者我需要改变我打算继续的方式?

最佳答案

如果你想枚举一个节点的所有子节点,你只需要使用类似 'Elementparent = root.getChild("parentNodeName")' 的方式获取你的父节点,然后你就可以用相同的方法枚举子节点'列出 child =parent.getChildren(“childName”)'。

    Document doc = null;
SAXBuilder sxb = new SAXBuilder();
try {
doc = sxb.build(new File(MyXmlFilePath));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element root = doc.getRootElement();
List<Element> nodes = root.getChildren("myNode");
Iterator<Element> it = nodes.iterator();
while(it.hasNext())
{
Element currentNode = it.next();
// node treatment here
}

安胡因。

关于java - 如何使用java制作动态xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4437639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com