繁体   English   中英

使用dom java解析xml

[英]parse xml using dom java

我有波纹管xml:

<modelingOutput>
    <listOfTopics>
        <topic id="1">
            <token id="354">wish</token>
        </topic>
    </listOfTopics>
    <rankedDocs>
        <topic id="1">
            <documents>
                <document id="1" numWords="0"/>
                <document id="2" numWords="1"/>
                <document id="3" numWords="2"/>
            </documents>
        </topic>
    </rankedDocs>
    <listOfDocs>
        <documents>
            <document id="1">
                <topic id="1" percentage="4.790644689978203%"/>
                <topic id="2" percentage="11.427632949428334%"/>
                <topic id="3" percentage="17.86913349249596%"/>
            </document>
        </documents>
    </listOfDocs>
</modelingOutput>

Ι想要解析此xml文件并从ListofDocs获取主题ID百分比

第一种方法是从xml获取所有文档元素,然后检查祖父节点是否为ListofDocs。 但元素文档存在于RankingDocslistOfDocs中 ,所以我有一个非常大的列表。

所以我想知道是否存在更好的解决方案来解析这个xml避免if语句?

我的代码:

public void parse(){
    Document dom = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));

    dom = db.parse(is);

    Element doc = dom.getDocumentElement();
    NodeList documentnl = doc.getElementsByTagName("document");
    for (int i = 1; i <= documentnl.getLength(); i++) {
        Node item = documentnl.item(i);
        Node parentNode = item.getParentNode();
        Node grandpNode = parentNode.getParentNode();
        if(grandpNode.getNodeName() == "listOfDocs"{
            //get value
        }
    } 
}

首先,在检查节点名称时,不应使用==比较String 始终使用equals方法。

您可以使用XPath仅评估listOfDocs下的文档topic元素:

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpression = xPath.compile("//listOfDocs//document/topic");

NodeList topicnl = (NodeList) xPathExpression.evaluate(dom, XPathConstants.NODESET);
for(int i = 0; i < topicnl.getLength(); i++) {
   ...

如果您不想使用if语句,可以使用XPath直接获取所需的元素。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("source.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/*/listOfDocs/documents/document/topic");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getAttributes().getNamedItem("id"));
    System.out.println(nodes.item(i).getAttributes().getNamedItem("percentage"));
}

在这里查看GitHub项目。

希望这可以帮助。

我喜欢使用XMLBeam执行此类任务:

public class Answer {

    @XBDocURL("resource://data.xml")
    public interface DataProjection {

        public interface Topic {
            @XBRead("./@id")
            int getID();

            @XBRead("./@percentage")
            String getPercentage();
        }

        @XBRead("/modelingOutput/listOfDocs//document/topic")
        List<Topic> getTopics();
    }

    public static void main(final String[] args) throws IOException {
        final DataProjection dataProjection = new XBProjector().io().fromURLAnnotation(DataProjection.class);
        for (Topic topic : dataProjection.getTopics()) {
            System.out.println(topic.getID() + ": " + topic.getPercentage());
        }
    }
}

甚至有一种方便的方法可以将百分比转换为floatdouble 告诉我你是否想要一个例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM