我在这里寻找解决方案,但从我的 xml 文档获取此属性时仍然遇到问题。我试图从中获取“1”:<update-comments total="1">
这里是我用来获取没有属性的其他值的代码:
DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
doc = dbBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("update");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String update_type = getValue("update-type", element);
String numLikes = null;
String submittedUrl = null;
String comments = null;
if (update_type.equals("SHAR")) {
String shar_user = null;
String timestamp = null;
String id = null;
String updateKey = null;
String numComments = null;
try {
shar_user = getValue("first-name", element)
+ " " + getValue("last-name", element);
timestamp = getValue("timestamp", element);
id = getValue("id", element);
updateKey = getValue("update-key", element);
profilePictureUrl = getValue("picture-url", element);
numLikes = getValue("num-likes", element);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private static String getValue(String tag, Element element)
{
NodeList nodes = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
最佳答案
此函数将使用与查找元素相同的策略从元素获取属性值。 (请注意,您的解决方案仅在元素实际存在时才有效。)
private static String getAttributeValue(String tag, Element element, String attribute)
{
NodeList nodes = element.getElementsByTagName(tag);
//note: you should actually check the list size before asking for item(0)
//because you asked for ElementsByTagName(), you can assume that the node is an Element
Element elem = (Element) nodes.item(0);
return elem.getAttribute(attribute);
}
关于java - 从 XML 文档获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25559330/