如何使用java获取xml节点的属性值

Pri*_*iya 18 java xml xmlnode xml-attribute

我有一个看起来像这样的xml:

{ <xml><ep><source type="xml">...</source><source type="text">..</source></ep></xml>}
Run Code Online (Sandbox Code Playgroud)

在这里,我想检索"源类型"的值,其中类型s属性.

我试过这样,但它不起作用:

 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = domFactory.newDocumentBuilder();
                    Document dDoc = builder.parse("D:/workspace1/ereader/src/main/webapp/configurations/config.xml");
                    System.out.println(dDoc);
                    XPath xPath = XPathFactory.newInstance().newXPath();
                    Node node = (Node) xPath.evaluate("//xml/source/@type/text()", dDoc, XPathConstants.NODE);
                    System.out.println(node);
                } catch (Exception e) {
                    e.printStackTrace();
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader("config.xml"));
            Document doc = builder.parse(is);

            NodeList nodeList = doc.getElementsByTagName("source");

            for (int i = 0; i < nodeList.getLength(); i++) {                
                Node node = nodeList.item(i);

                if (node.hasAttributes()) {
                    Attr attr = (Attr) node.getAttributes().getNamedItem("type");
                    if (attr != null) {
                        String attribute= attr.getValue();                      
                        System.out.println("attribute: " + attribute);                      
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

请帮助我!!

先谢谢,Varsha.

gks*_*gks 26

由于您的问题更通用,因此请尝试使用Java中提供的XML解析器来实现它.如果您需要特定于解析器,请在此处更新您已尝试过的代码

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
Run Code Online (Sandbox Code Playgroud)
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}
Run Code Online (Sandbox Code Playgroud)