【发布时间】:2011-05-23 05:20:17
【问题描述】:
我正在使用 Java 解析 Xml,我想在属性值的帮助下解析元素。
例如<tag1 att="recent">Data</tag1>
在此我想使用 att 值解析 tag1 数据。我是 java 和 xml 的新手。请指导我。
【问题讨论】:
-
“请指导我。”请正确拼写单词。顺便说一句 - 你有问题吗?
我正在使用 Java 解析 Xml,我想在属性值的帮助下解析元素。
例如<tag1 att="recent">Data</tag1>
在此我想使用 att 值解析 tag1 数据。我是 java 和 xml 的新手。请指导我。
【问题讨论】:
有很多方法可以做到这一点。您可以使用 xPath (example)、DOM Document 或 SAX Parser (example) 来检索属性值和标记元素。
以下是相关问题:
这是您所要求的解决方法。我绝不会建议这种类型的“hack”,而是使用 SAX(参见示例链接)。
public static Element getElementByAttributeValue(Node rootElement, String attributeValue) {
if (rootElement != null && rootElement.hasChildNodes()) {
NodeList nodeList = rootElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node subNode = nodeList.item(i);
if (subNode.hasAttributes()) {
NamedNodeMap nnm = subNode.getAttributes();
for (int j = 0; j < nnm.getLength(); j++) {
Node attrNode = nnm.item(j);
if (attrNode.getNodeType == Node.ATTRIBUTE_NODE) {
Attr attribute = (Attr) attrNode;
if (attributeValue.equals(attribute.getValue()) {
return (Element)subNode;
} else {
return getElementByAttributeValue(subNode, attributeValue);
}
}
}
}
}
}
return null;
}
PS:未提供代码注释。它作为练习提供给读者。 :)
【讨论】:
org.w3c.dom.Element element,你可以说String attribute = element.getAttribute("att");。
这是获取具有给定属性名称和值的子节点的 java 代码。这是你要找的吗
public static Element getNodeWithAttribute(Node root, String attrName, String attrValue)
{
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
Element el = (Element) n;
if (el.getAttribute(attrName).equals(attrValue)) {
return el;
}else{
el = getNodeWithAttribute(n, attrName, attrValue); //search recursively
if(el != null){
return el;
}
}
}
}
return null;
}
【讨论】:
这是一个老问题,但你可以使用 HTMLUnit
HtmlAnchor a = (HtmlAnchor)ele;
url = a.getHrefAttribute();
【讨论】: