【问题标题】:How to get xml attribute values using Document builder factory如何使用文档构建器工厂获取 xml 属性值
【发布时间】:2014-09-16 16:29:42
【问题描述】:

如何使用我得到的以下代码获取属性值;作为 msg 的输出。我想打印 MSID,type,CHID,SPOS,type,PPOS 值,任何人都可以解决这个问题。

String xml1="<message MSID='20' type='2635'>"
        +"<che CHID='501' SPOS='2'>"
        +"<pds type='S'>"
        +"<position PPOS='S01'/>"
        +"</pds>"
        +"</che>"
        +"</message>";

InputSource source = new InputSource(new StringReader(xml1));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String msg = xpath.evaluate("/message/che/CHID", document);
String status = xpath.evaluate("/pds/position/PPOS", document);

System.out.println("msg=" + msg + ";" + "status=" + status);

【问题讨论】:

    标签: java xml document


    【解决方案1】:

    你需要在你的 XPath 中使用@ 作为属性,而且你的第二个元素的路径说明符是错误的:

    String msg = xpath.evaluate("/message/che/@CHID", document);
    String status = xpath.evaluate("/message/che/pds/position/@PPOS", document);
    

    通过这些更改,我得到以下输出:

    msg=501;status=S01
    

    【讨论】:

    • 使用 xpath 会比使用 elements.getattribute 影响性能
    • @VBS:好吧,我只是按照您已经提供的代码进行操作...我假设您希望修复它而不是完全改变方法。您的问题根本没有提到性能。
    【解决方案2】:

    您可以使用Document.getDocumentElement() 获取根元素,使用Element.getElementsByTagName() 获取子元素:

    Document document = db.parse(source);
    
    Element docEl = document.getDocumentElement(); // This is <message>
    
    String msid = docEl.getAttribute("MSID");
    String type = docEl.getAttribute("type");
    
    Element position = (Element) docEl.getElementsByTagName("position").item(0);
    String ppos = position.getAttribute("PPOS");
    
    System.out.println(msid); // Prints "20"
    System.out.println(type); // Prints "2635"
    System.out.println(ppos); // Prints "S01"
    

    【讨论】:

    • 我相信使用 xpath 会更慢,但只要您使用小型 XML,您就不必担心性能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2011-05-07
    • 2013-02-22
    相关资源
    最近更新 更多