如何使用JDOM读取XML

时间:2015-03-02 14:59:20

标签: java jdom

如何获取此标记的值

<executingChannel><mnemonic>8</mnemonic></executingChannel>

使用JDOM

这个XML低
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
<SOAP-ENV:Header xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
<md:metadata xmlns:md="http://www.teste.net/cmm/services/metadata/v2.0">
    <serviceId>calculateEntityCache_Version_From_List</serviceId>
    <serviceVersion>1.0</serviceVersion>
    <institutionType>UNDEFINED</institutionType>
    <targetChannel>
    <mnemonic>8</mnemonic>
    </targetChannel>        
    <executingChannel>
    <mnemonic>8</mnemonic>
    </executingChannel>

&GT;

2 个答案:

答案 0 :(得分:0)

在JDOM中,您使用以下命令将文档读入内存:

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(source of XML ... URL, file, etc.);
Namespace md = Namespace.get("md",
         "http://www.teste.net/cmm/services/metadata/v2.0");

然后,您可以使用以下命令查询文档:

String path = "//md:metadata/executingChannel/mnemonic";
XPathExpression<Element> xp = XPathFactory.instance()
       .compile(path, Filters.element(), null, md);
Element mnemonic = xp.evaluateFirst(doc);
System.out.println(mnemonic.getText());

答案 1 :(得分:0)

以下是使用带有vtd-xml

的XPath表达式检索值的代码
import com.ximpleware.*;
public class simpleQuery {

    public static void main(String[] s) throws Exception{

        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("//targetChannel/mnemonic/text()");
        int i = ap.evalXPath();
        if (i!=-1)
            System.out.println(" result ==>"+vn.toString(i));
    }
}