我使用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)來檢索屬性值和標記元素。
這裏的相關問題:
這是一種變通方法,以你的要求是什麼。我絕不會建議這種類型的「黑客」,而是使用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。它作爲練習給讀者。 :)
感謝您的答覆。我想解析具有屬性的元素。你知道如何做到這一點..?我正在使用DOM概念 – RAAAAM 2011-05-23 05:33:44
是的,如果你有'org.w3c.dom.Element元素',你可以說'String attribute = element.getAttribute(「att」);'。 – 2011-05-23 05:51:35
再次感謝,〜String屬性= element.getAttribute(「att」);〜從這個我只得到屬性(即)無論我給我屬性我可以通過字符串,但我想解析元素的幫助下屬性。 – RAAAAM 2011-05-23 05:56:07
這是獲取具有給定屬性名稱和值的子節點的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();
「請指引我。」請妥善拼寫單詞。順便說一句 - 你有問題嗎? – 2011-05-23 05:40:14