我正试图使用 Java 从匹配属性名的 XML 文件中删除所有 xml 属性。 我目前被卡住了 。 在此代码的底部, 我能够在绕过时获得每个节点的属性值, 但我无法找到如何从节点中全部删除属性 。 有任何想法吗?
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class StripAttribute {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
org.w3c.dom.Document doc = null;
NodeList nodes = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse("a.xml");
nodes = doc.getChildNodes();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
for ( int i = 0; i < nodes.getLength(); i++ ) {
String id = nodes.item(i).getNodeValue();
if ( id.equals("siteKey")) {
Element el = ((Attr) nodes.item(i)).getOwnerElement();
el.removeAttribute(id);
}
}
Transformer transformer;
StreamResult result = null;
try {
transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
}
}
以下是我要变换的 XML 样本 :