【问题标题】:Looking for a specific child in XML using java使用 java 在 XML 中查找特定子项
【发布时间】:2015-11-14 20:04:07
【问题描述】:

过去几个小时我一直在寻找,但找不到方法。

我的 XML 文件:

<list>
	<Company id="01">
		<Name>Atari</Name>
		<Founded>1972</Founded>
		<Consoles>
			2600
			5200
			7800
		</Consoles>
	</Company>
	<Company id="02">
		<Name>Sega</Name>
		<Founded>1960</Founded>
		<Consoles>
			Master System
			Megadrive
			Saturn
		</Consoles>
	</Company>
</list>

基本上,我希望代码不仅可以找到一个公司区块中的名称,还可以找到我希望的任何公司区块中的名称,并且能够将其显示给其他类。到目前为止,我已经能够显示或,但只能通过直接更改代码而不是即时更改。我正在使用的代码:

    private static String getTextValue(String def, Element doc, String tag) {
    String value = def;
    NodeList nl;
    nl = doc.getElementsByTagName(tag);
    if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
        value = nl.item(0).getFirstChild().getNodeValue();
    }
    if(value==null) value = " ";
    return value;
}

public static boolean readXML(String xml) {
    rolev = new ArrayList<String>();
    Document dom;
    // Make an  instance of the DocumentBuilderFactory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // use the factory to take an instance of the document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // parse using the builder to get the DOM mapping of the    
        // XML file
        dom = db.parse(xml);

        Element doc = dom.getDocumentElement();

        role1 = getTextValue(role1, doc, "Name");
        if (getRole1() != null) {
            if (!getRole1().isEmpty())
                rolev.add(getRole1());
        }
        role2 = getTextValue(role2, doc, "Founded");
        if (role2 != null) {
            if (!role2.isEmpty())
                rolev.add(role2);
        }
        role3 = getTextValue(role3, doc, "Consoles");
        if (role3 != null) {
            if (!role3.isEmpty())
                rolev.add(role3);
        }
        role4 = getTextValue(role4, doc, "Name");
        if ( role4 != null) {
           if (!role4.isEmpty())
                rolev.add(role4);
        }
        return true;

    } catch (ParserConfigurationException pce) {
        System.out.println(pce.getMessage());
    } catch (SAXException se) {
        System.out.println(se.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    return false;
}

我使用了很多不同的方法,有些是搜索到的,有些是我自己制作的,但这是我能找到的最接近我需要的方法。不过,我需要能够随时更改它看起来的位置。

【问题讨论】:

标签: java xml


【解决方案1】:

您可以使用 xpath 来读取 XML。请参阅Parsing XML with XPath in Java 和/或How to read XML using XPath in Java

在您的情况下,如果您想获取所有公司名称,您将使用的设置路径(基本上是标签过滤器)将是“//list/Company/Name/text()”

其余的代码基本上可以从我贴的问题中复制过来。只有您的集合(过滤器)会有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多