【发布时间】:2017-01-06 04:26:59
【问题描述】:
我不知道如何解释我的情况,我可以在下面提供示例。 我有一个要在 Java 中读取的 XML 文件,如下所示:
<Author AffiliationIDS="Aff1">
<AuthorName DisplayOrder="Western">
<GivenName>Wei</GivenName>
<GivenName>Long</GivenName>
<FamilyName>
<Value>Tan</Value>
</FamilyName>
</AuthorName>
</Author>
如您所见<FamilyName> 标记,<FamilyName> 标记内部被一个值标记包围。这是因为在 xsd 中,它将元素声明为 maxOccurs="unbounded",这意味着该元素标签中可以包含多个值。无论Value 出现多少次,我应该如何修改代码以便它可以读取<FamilyName> 标签并获取Value 标签元素?
例子:
<FamilyName>
<Value>Sarah</Value>
<Value>Johnson</Value>
</FamilyName>
代码如下所示。
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/fileaddress/test-1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("AuthorName");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Given Name : " + eElement.getElementsByTagName("GivenName").item(0).getTextContent());
System.out.println("Family Name : " + eElement.getElementsByTagName("FamilyName").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】: