【问题标题】:How to get the value of subelement from XML?如何从 XML 中获取子元素的值?
【发布时间】:2022-01-31 11:05:42
【问题描述】:

我想在 JAVA 中从下面的 XML 中获取中间名的值。

<employee>
  <emp1 name='firstName'>FNAme</emp1>
  <emp1 name='middleName'>MNAme</emp1>
  <emp1 name='LastName'>LNAme</emp1>
</employee>

【问题讨论】:

  • 你已经尝试了什么?

标签: java xml xml-parsing


【解决方案1】:

这对我很有效: java代码

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class main
{
    public static void main(String[] args) {
        try {
            File file = new File(".idea/company.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(file);
            document.getDocumentElement().normalize();
            System.out.println("Root Element :" + document.getDocumentElement().getNodeName());
            NodeList nList = document.getElementsByTagName("employee");
            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("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
                    System.out.println("Middle Name : " + eElement.getElementsByTagName("middleName").item(0).getTextContent());
                    System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
                }
            }
        }
        catch(IOException | ParserConfigurationException | SAXException e) {
            System.out.println(e);
        }

xml 看起来像这样:

<?xml version="1.0"?>
<company>
    <employee>
        <firstName>FNAme</firstName>
        <middleName>MNAme</middleName>
        <lastName>LNAme</lastName>
    </employee>
</company>

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多