以下代码是使用DOM解析器来反转XML。一切正常,但问题是属性没有逆转 对于前: < element att1 =" foo" ATT2 ="杆" /> 结果应该是 < element att2 =" bar" ATT2 ="富" />
如何反转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)<!--.*?-->", "" ));
}
答案 0 :(得分:3)
根据定义,XML属性不是有序的。它们在XML文档中的出现(在其包含元素中)完全受到某些XML编写器的实现的支配。
没有XML处理器可以基于属性外观顺序的任何逻辑。
那就是说,你应该满足于能够扭转元素。