3

这是我的xml代码...

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

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

4

6 回答 6

8

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);
于 2012-11-13T06:51:06.190 回答
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 工作,那很好 - 如果您正在做大量工作,我只是觉得它们有点原始。)

于 2012-11-13T06:58:05.507 回答
0

使用 xpath 这里有更多信息:

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

于 2012-11-13T06:48:38.480 回答
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/

于 2012-11-13T07:10:25.880 回答
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();
        }

    }
}
于 2016-02-13T14:14:44.827 回答
-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();
    }
}
于 2018-05-23T05:58:25.793 回答