【问题标题】:how to get the attribute value of an xml node using java如何使用java获取xml节点的属性值
【发布时间】:2012-08-05 11:25:02
【问题描述】:

我有一个如下所示的 xml:

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

这里我想检索“源类型”的值,其中 type 是一个属性。

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

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

我也试过了:

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

请帮帮我!!

提前致谢, 瓦尔沙。

【问题讨论】:

  • 您是否尝试过使用VTD-XML vtd-xml.sourceforge.net 它更快,内存效率更高。
  • 嗨 Rosdi,不,我没试过,反正 ATR 的代码工作正常,我的 sn-p 也是:) 感谢您的友好回复

标签: java xml xmlnode xml-attribute


【解决方案1】:

由于您的问题更通用,因此请尝试使用 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);
}

【讨论】:

  • 我已经尝试了上面的 sn-p 并且我不继续,请帮助我!我需要单独获取值“xml”和“text”。这是我的要求。
  • ATR,它实际上是 //xml/ep/source/@type 我在你的代码中编辑了一些语句..它工作正常..谢谢:)
  • 有没有办法在标签之间获取值,在上面的示例中,TEST,我如何阅读 TEST
【解决方案2】:

试试这样的:

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

请注意更改:

  • 我们要求一个节点集 (XPathConstants.NODESET) 而不仅仅是单个节点。
  • xpath 现在是 //xml/ep/source/@type 而不是 //xml/source/@type/text()

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

【讨论】:

  • mabroukb,谢谢:) 添加了 java 标签:) 你的解释让我很清楚.. 非常感谢!!
【解决方案3】:

我很高兴这个 sn-p 工作正常:

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

【讨论】:

    【解决方案4】:

    使用

    document.getElementsByTagName(" * ");

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

    示例:

    NodeList 列表 = doc.getElementsByTagName("*");


    System.out.println("XML 元素:");

            for (int i=0; i<list.getLength(); i++) {
    
                Element element = (Element)list.item(i);
                System.out.println(element.getNodeName());
            }
    

    【讨论】:

      【解决方案5】:

      下面是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));
      
               }
           }
      }
      

      【讨论】:

        【解决方案6】:
        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);
                }
            }
        

        我们可以用方法试试这段代码

        【讨论】:

          【解决方案7】:

          以下是我编写的实用方法,用于从根 Document 对象和给定 XPATH 获取任何节点的值。

          public String getValue(Document doc, String xPath) throws Exception {
             XPathFactory factory = XPathFactory.newInstance();
             XPath path = factory.newXPath();
             XPathExpression expression = path.compile(xPath);
             Node node = (Node) expression.evaluate(doc,XPathConstants.NODE);
             return node.getFirstChild().getNodeValue();
          }
          

          所有的库都来自 java.xml.xpathorg.w3c.dom。

          现在您只需要根文档元素和正确的路径。 对于你的例子,如果 /ep/source/@type

          所以,XPAth 基本上是导航到您所关注的元素,然后是您感兴趣的 /@attributeName

          请节点 /ep/source@type 不起作用。 (我浪费了 30 分钟来解决这个问题)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多