我试图获取示例 XML
文件中每个人的姓名,但得到的是 null
值而不是他们的姓名。
Java代码:
package testjdom;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class TestJDOM {
public static void main(String[] args) throws
JDOMException,
IOException {
SAXBuilder jdomBuilder
= new SAXBuilder();
Document jdomDocument
= jdomBuilder.build("persons.xml");
Element jdomRoot = jdomDocument.getRootElement();
List<Element> children = jdomRoot.getChildren();
for (Element child : children) {
System.out.println(child.getAttributeValue("name"));
}
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<id>1</id>
<name>The Best</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b676a616a777b6d66687b676661684f68626e6663216c6062" rel="noreferrer noopener nofollow">[email protected]</a></email>
<birthDate>1981-11-23</birthDate>
</person>
<person>
<id>2</id>
<name>Andy Jr.</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bcbaa889aea4a8a0a5e7aaa6a4" rel="noreferrer noopener nofollow">[email protected]</a></email>
<birthDate>1982-12-01</birthDate>
</person>
<person>
<id>3</id>
<name>JohnDoe</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3b5b9b1bba2b1a694b3b9b5bdb8fab7bbb9" rel="noreferrer noopener nofollow">[email protected]</a></email>
<birthDate>1990-01-02</birthDate>
</person>
<person>
<id>4</id>
<name>SomeOne</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="017374626a7260626a41666c60686d2f626e6c" rel="noreferrer noopener nofollow">[email protected]</a></email>
<birthDate>1988-01-22</birthDate>
</person>
<person>
<id>5</id>
<name>Mr. Mxyzptlk</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36545f515b5758765e59425b575f5a1855595b" rel="noreferrer noopener nofollow">[email protected]</a></email>
<birthDate>1977-08-12</birthDate>
</person>
</persons>
如何获取每个名称的真实值?
最终我想从 XML 中获取每个人的四个值。我有一个名为 Person 的类,它具有与 XML 文件中的人员相同的属性、id、名称等。我想从“Person”类创建新对象,并使用XML 中的数据。当我创建一个新对象并使用从 XML 获取的值成功设置其属性时,我想将该对象添加到 ArrayList,然后对其余人员重复相同的过程。
最佳答案
你有两个问题。 name
不是一个属性,它是一个子元素。其次,getChildren()
仅下降一级。
改变
Element jdomRoot = jdomDocument.getRootElement();
List<Element> children = jdomRoot.getChildren();
for (Element child : children) {
System.out.println(child.getAttributeValue("name"));
}
至
Element jdomRoot = jdomDocument.getRootElement();
List<Element> people = jdomRoot.getDescendants(new ElementFilter("person"));
for (Element person: people) {
System.out.println(person.getChild("name").getText());
}
关于java - 无法使用 JDOM 从 XML 获取子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51939194/