gpt4 book ai didi

Java - 反转 XML 属性

转载 作者:行者123 更新时间:2023-12-01 22:54:21 25 4
gpt4 key购买 nike

下面的代码是使用 DOM 解析器反转 XML。一切正常,但问题是属性不反转例如: 结果应该是

如何反转XML属性?

public static void main(String[] args) throws Exception {
reverseChildElements();
}

public static void reverseChildElements() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse the input xml file
doc = builder.parse("file.xml");
Node firstChild = doc.getFirstChild();
reverseChildNodes(firstChild);
doc.replaceChild(firstChild, doc.getFirstChild());
outputXml(doc);
} catch (ParserConfigurationException | SAXException | IOException | TransformerException e) {
e.printStackTrace();
}
}

private static void reverseChildNodes(Node firstChild) {
NodeList childNodes = firstChild.getChildNodes();
Stack<Node> nodeStack = new Stack<Node>();
// Put all the nodes into a Stack
for (int i = 0; i < childNodes.getLength(); i++) {
reverseChildNodes(childNodes.item(i));
revereseAttributes(childNodes.item(i));
nodeStack.push(childNodes.item(i));
}
// This is the last one which we entered
while (!nodeStack.empty()) {
firstChild.appendChild(firstChild.removeChild(nodeStack.pop()));
}
}

private static void revereseAttributes(Node item) {
if(item.hasAttributes() && item.getAttributes().getLength() > 1){
NamedNodeMap attributesMap = item.getAttributes();
List<Node> nodeStack = new ArrayList<Node>();
for (int i = 0; i < attributesMap.getLength(); i++) {
nodeStack.add(attributesMap.item(i));
}
for (Node node : nodeStack) {
attributesMap.removeNamedItem(node.getNodeName());
Attr atr = node.getOwnerDocument().createAttribute(node.getNodeName());
atr.setValue(node.getNodeValue());
attributesMap.setNamedItem(atr);
}
}

}

private static void outputXml(Document doc) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
StringWriter writer = null;
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
"yes");
writer = new StringWriter();

transformer.transform(new DOMSource(doc), new StreamResult(writer));
System.out.println(writer.toString().replaceAll( "(?s)<!--.*?-->", "" ));
}

最佳答案

根据定义,XML 属性是无序的。它们在 XML 文档中的出现(在其包含元素内)完全取决于某些 XML 编写器的实现。

任何 XML 处理器都不能基于属性出现顺序的任何逻辑。

也就是说,您应该对能够反转元素感到满意。

关于Java - 反转 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312025/

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