如何使用java中的循环读取XML子节点值

时间:2012-11-13 06:42:58

标签: java xml

这是我的xml代码......

<flow>
    <TaskID>100</TaskID>
    <TaskID>101</TaskID>
    <TaskID>102</TaskID>
    <TaskID>103</TaskID>    
</flow>

我想知道如何在java中的for循环中获取taskID值。请帮帮我......

6 个答案:

答案 0 :(得分:6)

DOM解析器解决方案,相当简单,无需额外的库。

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    String input = "<outer>";
    input += "<otherstuff><TaskID>123</TaskID></otherstuff>";
    input += "<flow>";
    input += "<TaskID>100</TaskID>";
    input += "<TaskID>101</TaskID>";
    input += "<TaskID>102</TaskID>";
    input += "<TaskID>103</TaskID>";
    input += "</flow>";
    input += "</outer>";
    Document document = builder.parse(new InputSource(new StringReader(
            input)));

    NodeList flowList = document.getElementsByTagName("flow");
    for (int i = 0; i < flowList.getLength(); i++) {
        NodeList childList = flowList.item(i).getChildNodes();
        for (int j = 0; j < childList.getLength(); j++) {
            Node childNode = childList.item(j);
            if ("TaskID".equals(childNode.getNodeName())) {
                System.out.println(childList.item(j).getTextContent()
                        .trim());
            }
        }
    }
}

如果输入来自文件,则需要使用FileReader。

Document document = builder.parse(new InputSource(new FileReader(
        new File("foo.xml"))));

getElementsByTagName()的替代方法是XPath,一种XML的查询语言,如果您有一组复杂的条件要匹配,这将特别有用。

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//flow/TaskID/text()");

Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getTextContent());
}

如果您的XML文件很大,例如100 MB / GB或者您在低内存平台上,那么请考虑使用SAX解析器。

String input = "<flow><TaskID>100</TaskID><TaskID>101</TaskID><TaskID>102</TaskID><TaskID>103</TaskID></flow>";
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new DefaultHandler() {
    private StringBuilder buffer = new StringBuilder();
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("TaskID".equals(qName)) {
            System.out.println(buffer);
            buffer = new StringBuilder();
        }
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        buffer.append(ch, start, length);
    }
    @Override
    public void startElement(String uri, String localName,
            String qName, Attributes attributes) throws SAXException {
        buffer = new StringBuilder();
    }
};
sax.parse(new InputSource(new StringReader(input)), handler);

答案 1 :(得分:4)

以下是使用JDOM的示例,它提供了比现有Java XML解析器更令人愉快的API:

import java.io.File;
import org.jdom2.*;
import org.jdom2.input.*;

public class Test {
    // TODO: More appropriate exception handling :)
    public static void main (String[] args) throws Exception {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new File("test.xml"));
        Element root = doc.getRootElement();
        for (Element element : root.getChildren("TaskID")) {
            System.out.println(element.getText());
        }
    }
}

当然,这假设XML文档足够小,无法加载到内存中。

(显然你也可以使用内置的库,如果你没有做很多 XML工作,那就没问题了 - 如果你做的话,我发现它们有点原始任何大量的工作。)

答案 2 :(得分:0)

使用xpath以下是更多信息:

http://www.vogella.com/articles/JavaXML/article.html

答案 3 :(得分:0)

我个人使用JDOM库进行所有XML操作。以下是我将如何操作;

 String xml = "<flow> " +
                   "<TaskID>100</TaskID>" +
                   "<TaskID>101</TaskID>" +
                   "<TaskID>102</TaskID>" + 
                   "<TaskID>103</TaskID>" + 
              "</flow>";

org.jdom.Document doc = new SAXBuilder().build(new StringReader(xml));

org.jdom.Element rootElement = doc.getRootElement();

List<Element> eles = rootElement.getChildren("TaskID");

for(Element el : eles)
   System.out.println(el.getName()+" : "+el.getValue());

您可以在此处获取文档:http://www.jdom.org/

答案 4 :(得分:0)

使用SAX阅读Xml儿童

<?xml version="1.0"?> 
<Patriarch>
   <name>Bill</name>
   <wife>
      <name>Vi</name>
   </wife>
   <son>
      <name>Bill</name>
   </son>
   <daughter>
      <name>Jeri</name>
      <husband>
         <name>Mark</name>
      </husband>
      <son>
         <name>Greg</name>
      </son>
      <son>
         <name>Tim</name>
      </son>
      <son>
         <name>Mark</name>
      </son>
      <son>
         <name>Josh</name>
         <wife>
            <name>Kristine</name>
         </wife>
         <son>
            <name>Blake</name>
         </son>
         <daughter>
            <name>Liah</name>
         </daughter>
      </son>
   </daughter>
</Patriarch>

和Java代码:

public class ParseXmlSAX {

    public static void main(String[] args) {
        new ParseXmlSAX("file.xml");
    }

    public ParseXmlSAX(final String file) {
        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {
                String key = null;

                public void startElement(String uri, String localName, String qName, Attributes attributes)
                        throws SAXException {

                    if (key == null)
                        key = "|";
                    else
                        key += qName + "|";

                }

                public void endElement(String uri, String localName, String qName) throws SAXException {

                    if (!key.equals("|"))
                        key = key.substring(0, key.lastIndexOf(qName));

                }

                public void characters(char ch[], int start, int length) throws SAXException {
                    String conteudo = new String(ch, start, length).trim();

                    if (!conteudo.isEmpty()) {
                        System.out.println(key + " = " + conteudo);
                    }

                }

            };

            saxParser.parse(this.getClass().getResourceAsStream(file), handler);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

答案 5 :(得分:-1)

public class Modifier {

    public void modifyXML() {
        String strSrcFile = "E:\\projects\\input\\sample.xml";
        String strOutputFile = "E:\\projects\\output\\sample.xml";
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(strSrcFile);
            Node company = doc.getFirstChild();
            System.out.println(company.hasChildNodes());
            NodeList nl = company.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                // System.out.println("inner node::"+node.getNodeName());

                if (node.hasChildNodes()) {
                    System.out.println("outer node::" + node.getNodeName());
                    readChildNodes(node);
                } else {

                }
            }

            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(strOutputFile));
            transformer.transform(source, result);

        } catch (Exception ee) {
            ee.printStackTrace();
        }
        // Get the root element

    }

    public void readChildNodes(Node node)
    {

        NodeList nl = node.getChildNodes();


        for (int i = 0; i < nl.getLength(); i++) {
            Node innernode = nl.item(i);
            //System.out.println("mediam stage  node::"+innernode.getNodeName());
            if (innernode.hasChildNodes()) {
                System.out.println("inner node::"+innernode.getNodeName());

                readChildNodes(innernode);
            }
            else{

                System.out.println("node dont have childs node::"+innernode.getNodeName());
            }

        }
    }

    public void replaceGraphicCode(Node innernode) {
        NamedNodeMap attr = innernode.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        String IDvalue = nodeAttr.getTextContent();


        // nodeAttr.setTextContent("2");
    }

    public void replaceOriginator(Node innernode) {
        NamedNodeMap attr = innernode.getAttributes();
        Node nodeAttr = attr.getNamedItem("enterpriseCode");


    }

    public static void main(String[] args) {
        Modifier objModifier = new Modifier();
        objModifier.modifyXML();
    }
}