2

次のような XML ファイルがあります。

<?xml version="1.0" encoding="utf-8"?>
<RootElement>
 <Achild>
  .....
 </Achild>
 </RootElement>

ファイルに要素が含まれているかどうかを確認するにはどうすればよいAchildですか..?

            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // Use the factory to create a builder
    try {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(configFile);
        final Node parentNode = doc.getDocumentElement();
        final Element childElement = (Element) parentNode.getFirstChild();
                    if(childElement.getNodeName().equalsIgnoreCase(....

しかし、childElement is nullでエラーが発生します....

4

3 に答える 3

1
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("foo.xml"));

XPath xPath = XPath.newInstance("/RootElement/Achild");

/*If you want to find all the "Achild" elements 
and do not know what the document structure is, 
use the following XPath instead(less efficient):
XPath xPath = XPath.newInstance("//Achild");
*/

Element aChild = (Element) xPath.selectSingleNode(document);

if(aChild == null){
  //There is at least one "Achild" element in the document
} else{
  //No "Achild" elements found
}
于 2011-07-11T11:15:17.253 に答える
0
List children = root.getChildren("Achild");
int サイズ = children.size();

子が含まれているかどうかにかかわらず、サイズを確認します。

于 2011-07-11T09:50:55.797 に答える
0

あなたのコードでは、ビルダーを作成しているだけですが、何をビルドしますか?? DOM ツリーを作成するために使用するファイルを指定する必要はありません... JDom を使用した小さな例を以下に示します..

    try {
        SAXBuilder builder = new SAXBuilder();
        File XmlFile = new File("Xml_File_Path");
        docXml = builder.build(XmlFile.getPath());
        Element root = docXml.getRootElement();
        if (root.getChildren("aChild") == Null)
            do_whateva_you_want
        else
            great_i_can_keep_up

    } catch (JDOMException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
于 2011-07-12T06:34:04.200 に答える