繁体   English   中英

Java xml解析具有相同名称的两个标签

[英]Java xml Parsing For Two Tags with Same Name

我正在编写代码以解析xml文件。 我想从中检索国家标签值,并将其保存到String []。 当我尝试这样做时,它仅检索一个值。 但是我在xml中重复了两次国家标签。 将来可能是三次或四次,以此类推。 这是我的xml:

<?xml version="1.0"?>
<metadata>
<Country>All Countries</Country>
<Country>US - United States</Country>
</metadata>

这是我的代码:

private static String parseXml(String xmlData)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
    InputSource src = new InputSource();
    src.setCharacterStream(new StringReader(xmlData));
    Document doc = builder.parse(src);
    NodeList nodes = doc.getElementsByTagName("metadata");
    Element line = null;
    String cnt = null;
    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        NodeList country = element.getElementsByTagName("Country");
        for (int j = 0; j < country.getLength(); j++) {
            if (country != null) {
                System.out.println("Country not null " + country);
                line = (Element) country.item(0);
                if (line != null) {
                    cnt = getCharacterDataFromElement(line);
                }
            }
        }
    }
    return cnt;

}

public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        if (cd != null) {
            return cd.getData();
        }
    }
    return "";
}

尽管您的代码会遍历所有国家/地区,但您无法在代码中存储国家/地区列表。

以下内容将有所帮助(尽管未经测试):Change String cnt = null; List<String> = new ArrayList<String>()并代替

for (int j = 0; j < country.getLength(); j++) {
    if (country != null) {
        System.out.println("Country not null " + country);
        line = (Element) country.item(0);
        if (line != null) {
            cnt = getCharacterDataFromElement(line);
        }
    }
}

下列:

if (country != null) {
    System.out.println("Country not null " + country);
    for (int j = 0; j < country.getLength(); j++) {
        line = (Element) country.item(j);
        if (line != null) {
            cnt.add( getCharacterDataFromElement(line));
        }
    }
}

您需要在程序中进行两次修改

  1. item(0)应替换为item(j)

  2. 您可以使用line.getFirstChild().getNodeValue()获得国家/地区的值

下面是更新的类XmlParser.java

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlParser {


    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        String xml = "<?xml version=\"1.0\"?> "
                + "<metadata> "
                + "<Country>All Countries</Country> "
                + "<Country>US - United States</Country> "
                + "</metadata>";
        parseXml(xml);
    }

    private static String parseXml(String xmlData)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(xmlData));
        Document doc = builder.parse(src);
        NodeList nodes = doc.getElementsByTagName("metadata");
        Element line = null;
        String cnt = null;
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            NodeList country = element.getElementsByTagName("Country");
            for (int j = 0; j < country.getLength(); j++) {
                if (country != null) {
                    System.out.println("Country not null " + country);
                    line = (Element) country.item(j);
                    System.out.println("value :: " + line.getFirstChild().getNodeValue());
                }
            }
        }
        return cnt;

    }

    public static String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof org.w3c.dom.CharacterData) {
            org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;
            if (cd != null) {
                return cd.getData();
            }
        }
        return "";
    }
}

output如下:

国家/地区不为空com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl@51f45f2a value ::所有国家

国家/地区不为空com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl@51f45f2a值::美国-美国

尝试这个:

public class Test {

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
        System.out
            .println(Arrays
                    .toString(parseXml("<?xml version=\"1.0\"?><metadata><Country>All Countries</Country><Country>US - United States</Country></metadata>")));
    }

    private static String[] parseXml(String xmlData) throws SAXException, IOException, ParserConfigurationException {
        ArrayList<String> list = new ArrayList<String>();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(xmlData));
        Document doc = builder.parse(src);
        NodeList nodes = doc.getElementsByTagName("metadata");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            NodeList country = element.getElementsByTagName("Country");
            for (int j = 0; j < country.getLength(); j++) {
                list.add(country.item(j).getTextContent());
            }
        }
        return list.toArray(new String[list.size()]);
    }
}
private static String[] getCountries(String xmlData) throws Exception{
    List<String> result = new ArrayList<String>();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource src = new InputSource(new StringReader(xmlData));
    Document doc = builder.parse(src);
    NodeList nodes = doc.getElementsByTagName("metadata");
    for(int i = 0; i < nodes.getLength(); i++){
        Element metadata = (Element)nodes.item(i);
        NodeList countries = metadata.getElementsByTagName("Country");
        for(int j = 0; j < countries.getLength(); j++){
            result.add(countries.item(j).getTextContent());
        }
    }
    return result.toArray(new String[result.size()]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM