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

时间:2022-11-27 17:15:16

I've an xml which looks like this:

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

{ <xml><ep><source type="xml">...</source><source type="text">..</source></ep></xml>}

here i wanna retrieve the value of "source type" where type s an attribute.

在这里,我想检索“源类型”的值,其中类型s属性。

I 'd tried like this,But its not working:

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

 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();

i've tried this too :

我也试过这个:

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);                      
                    }
                }
            }

pls help me!!

请帮助我!!

Thanks in advance, Varsha.

先谢谢,Varsha。

6 个解决方案

#1


20  

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

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

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
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);
}

#2


3  

try something like this :

尝试这样的事情:

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

请注意更改:

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • 我们要求一个节点集(XPathConstants.NODESET),而不仅仅是一个节点。
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()
  • xpath现在是// xml / ep / source / @ type而不是// xml / source / @type / text()

PS: can you add the tag java to your question ? thanks.

PS:你可以在你的问题中添加标签java吗?谢谢。

#3


1  

use

使用

document.getElementsByTagName(" * ");

document.getElementsByTagName(“*”);

to get all XML elements from within an XML file, this does however return repeating attributes

要从XML文件中获取所有XML元素,但这会返回重复的属性

example:

例:

NodeList list = doc.getElementsByTagName("*");

NodeList list = doc.getElementsByTagName(“*”);


System.out.println("XML Elements: ");

System.out.println(“XML Elements:”);

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }

#4


0  

I'm happy that this snippet works fine:

我很高兴这个片段工作正常:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("config.xml"));
NodeList nodeList = document.getElementsByTagName("source");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
    System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());
} 

#5


0  

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

我们可以使用方法尝试这个代码

#6


0  

Below is the code to do it in VTD-XML

下面是在VTD-XML中执行此操作的代码

import com.ximpleware.*;

public class queryAttr{
     public static void main(String[] s) throws VTDException{
         VTDGen vg= new VTDGen();
         if (!vg.parseFile("input.xml", false))
            return false;
         VTDNav vn = vg.getNav();
         AutoPilot ap = new AutoPilot(vn);
         ap.selectXPath("//xml/ep/source/@type");
         int i=0;
         while((i = ap.evalXPath())!=-1){
               system.out.println(" attr val ===>"+ vn.toString(i+1));

         }
     }
}

#1


20  

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

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

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
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);
}

#2


3  

try something like this :

尝试这样的事情:

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

请注意更改:

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • 我们要求一个节点集(XPathConstants.NODESET),而不仅仅是一个节点。
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()
  • xpath现在是// xml / ep / source / @ type而不是// xml / source / @type / text()

PS: can you add the tag java to your question ? thanks.

PS:你可以在你的问题中添加标签java吗?谢谢。

#3


1  

use

使用

document.getElementsByTagName(" * ");

document.getElementsByTagName(“*”);

to get all XML elements from within an XML file, this does however return repeating attributes

要从XML文件中获取所有XML元素,但这会返回重复的属性

example:

例:

NodeList list = doc.getElementsByTagName("*");

NodeList list = doc.getElementsByTagName(“*”);


System.out.println("XML Elements: ");

System.out.println(“XML Elements:”);

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }

#4


0  

I'm happy that this snippet works fine:

我很高兴这个片段工作正常:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("config.xml"));
NodeList nodeList = document.getElementsByTagName("source");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
    System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());
} 

#5


0  

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

我们可以使用方法尝试这个代码

#6


0  

Below is the code to do it in VTD-XML

下面是在VTD-XML中执行此操作的代码

import com.ximpleware.*;

public class queryAttr{
     public static void main(String[] s) throws VTDException{
         VTDGen vg= new VTDGen();
         if (!vg.parseFile("input.xml", false))
            return false;
         VTDNav vn = vg.getNav();
         AutoPilot ap = new AutoPilot(vn);
         ap.selectXPath("//xml/ep/source/@type");
         int i=0;
         while((i = ap.evalXPath())!=-1){
               system.out.println(" attr val ===>"+ vn.toString(i+1));

         }
     }
}