21

我有一个看起来像这样的 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);                      
                    }
                }
            }

请帮助我!!

在此先感谢,瓦尔沙。

4

7 回答 7

32

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

<?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);
}
于 2012-08-08T11:15:05.667 回答
4

尝试这样的事情:

    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 添加到您的问题中吗?谢谢。

于 2012-08-08T14:53:12.920 回答
1

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

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());
} 
于 2012-08-09T05:00:43.697 回答
1

采用

document.getElementsByTagName(" * ");

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

例子:

NodeList list = 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());
        }
于 2014-12-22T13:49:39.630 回答
1

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

         }
     }
}
于 2016-04-26T00:25:40.423 回答
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);
        }
    }

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

于 2016-02-09T13:41:54.160 回答
0

下面是我编写的实用方法,用于从根 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 分钟来解决这个问题)。

于 2021-09-10T09:04:18.153 回答