我们有一个以 XML 文档形式返回搜索结果的目录。
<directory.person>
<person netid="" pidm="" student="" affiliate="">
<picture>no</picture>
<name>...</name>
</person>
我正在尝试使用以下代码在 java 中解析和读取它:
try{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("person");
for(int i = 0;i < nodes.getLength(); i++){
Element element = (Element) nodes.item(i);
NodeList pidm = element.getElementsByTagName("@pidm");
Element line = (Element)pidm.item(0);
value = getCharacterDataFromElement(line);
if(value.compareTo("Dana")==0 || value=="Dana")
out.println(value);
}
}
catch(Exception e){
out.println(e);
}
我遇到的问题是在我的“for”循环的第二行中实际访问该 pidm 变量。我不知道该怎么做。基本上,我需要通过 pidm 输出,因为这是返回的每个人的唯一标识符。我知道 jSTL 会更容易,但这里的人不想那样做。
最佳答案
org.w3c.dom.Element
类有许多访问元素属性的方法。
此处最简单的情况是调用 element.getAttribute("pidm");
。
它将为您提供给定属性的值。
否则,为了您的方便,您可以浏览 Element
的其他 getAttribute...
方法。
API here .
关于java - 在 java 中访问 xml 元素中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390839/