从xml标记获取数据

时间:2016-03-03 11:23:02

标签: java xml xml-parsing

如何从Java中的xml标签获取文本? 例如,这是xml文件:

<text data="word"/>

这是我的代码:

DocumentBuilderFactory documentBuilderFactory= DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
            Document document=documentBuilder.parse(url);
            document.normalizeDocument();
            NodeList el=document.getElementsByTagName("data");
            System.out.println(el.getTextContent());

2 个答案:

答案 0 :(得分:0)

使用此

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(filename));//filename=xml filename
        Element root = (Element) doc.getDocumentElement();
        NodeList requestNodeList = root
                .getElementsByTagName("TALLYREQUEST");


        String requestName = null;
        if (requestNodeList.getLength() > 0) {
            requestName = requestNodeList.item(0).getTextContent();
        }

现在检索xml文件的每个节点

       NodeList nodes = root.getElementsByTagName("TALLYMESSAGE");

        for (int i = 0; i < nodes.getLength(); i++) {
            Node tallyMessageNode = nodes.item(i);
            if (tallyMessageNode.getNodeType() == Node.ELEMENT_NODE) {
                 Common.print(tallyMessageNode.getNodeName());
                NodeList tallyMessageNodeList = tallyMessageNode
                        .getChildNodes();
                for (int j = 0; j < tallyMessageNodeList.getLength(); j++) {
                    Node subNode = tallyMessageNodeList.item(j);
                    if (subNode.getNodeType() == Node.ELEMENT_NODE) {
                 // code corresponding to your xml file.
                 // node.getAttributes().getNamedItem("NODE NAME")
              }

答案 1 :(得分:0)

您可以使用像Jsoup这样的HTML解析器 下载jar文件并将其添加到项目中。然后简单地说:

String html = "<text data=word />";
Document document = Jsoup.parse(html);
Element element = document.select("text").first();
String str = element.attr("data");
System.out.println(str);

如果您有多个<text>标签,则可以像这样使用

Elements elements = document.select("text");