您可以将 XPath 与表达式查询“//*[@base64]”一起使用。
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new File("your_xml.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//*[@base64]";
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String base64 = element.getAttribute("base64");
element.removeAttribute("base64");
}
String newXML = getStringFromNode(document);
}
catch (Exception e) {
}
getStringFromNode 方法
public static String getStringFromNode(Node root) {
StringBuilder result = new StringBuilder();
if (root.getNodeType() == 3)
result.append(root.getNodeValue());
else {
if (root.getNodeType() != 9) {
StringBuffer attrs = new StringBuffer();
for (int k = 0; k < root.getAttributes().getLength(); ++k) {
attrs.append(" ").append(
root.getAttributes().item(k).getNodeName()).append(
"=\"").append(
TextUtils.htmlEncode(root.getAttributes().item(k).getNodeValue()))
.append("\" ");
}
result.append("<").append(root.getNodeName()).append(" ")
.append(attrs).append(">");
} else {
result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
NodeList nodes = root.getChildNodes();
for (int i = 0, j = nodes.getLength(); i < j; i++) {
Node node = nodes.item(i);
result.append(getStringFromNode(node));
}
if (root.getNodeType() != 9) {
result.append("</").append(root.getNodeName()).append(">");
}
}
return result.toString();
}
已编辑
同样也可以用于解析字符串。请参阅下面的方法,它将字符串解析为 DOM 文档。现在您可以将此文档用作 XPath 的输入。
public static Document ReadDocument(String xml)
{
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
StringReader reader = new StringReader(xml);
is.setCharacterStream(reader);
doc = db.parse(is);
} catch (Exception e) {
Log.e("Error", "Error while Parsing Document", e);
return null;
}
return doc;
}