简体   繁体   English

如何使用 java 从 xml 中的 id 获取 parant 标签内的特定标签内容?

[英]how to get specific tag content inside parant tag from id in xml using java?

I have an XML file as below.我有一个 XML 文件如下。 I want to get its specific child tag from the parent tag using java.我想使用 java 从父标签获取其特定的子标签。

<?xml version="1.0"?>  
<class>  
    
  <question  id="scores">
        <ans>12</ans>
        <ans>32</ans>
        <ans>44</ans>
  </question>

  <question  id="ratings">
        <ans>10</ans>
        <ans>22</ans>
        <ans>45</ans>
        <ans>100</ans>
  </question>
<default>
    Sorry wrong
</default>
  </class>  

i want the function to be like this我希望 function 是这样的

String function(String id)

it will return the ans tag randomly它会随机返回ans标签
ie if I give input id=scores, the program will look in the XML tag for scores as id and get length()of its children, in this case, 3, then retun randomly like 32 or 44 or 12.if id is not present, return default.即,如果我输入 id=scores,程序将在 XML 标签中查找作为 id 的分数并获取其子项的 length(),在本例中为 3,然后随机重新调整,如 32 或 44 或 12。如果 id 不是存在,返回默认值。

my code so far到目前为止我的代码

public class ChatBot {
    
    private String filepath="E:\\myfile.xml";
    private File file;
    private Document doc;

    public ChatBot() throws SAXException, IOException, ParserConfigurationException {
         file = new File("E:\\myfile.xml");  
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
         DocumentBuilder db = dbf.newDocumentBuilder();  
         doc = db.parse(file); 
    }
    
    
    String Function(String id){
// This part
            return null;
    }
       
    }

As suggested by @LMC (because of org.w3c.dom.Document.getElementById() not recognizing arbitrary id attributes as IDs for getElementById() or as a browser would, mostly for HTML semantics/format), maybe:正如@LMC 所建议的(因为org.w3c.dom.Document.getElementById()无法将任意id属性识别为getElementById()的 ID 或浏览器会识别的 ID,主要针对 HTML 语义/格式),也许:

    String Function(String id) throws XPathExpressionException {
        XPath xPath = XPathFactory.newInstance().newXPath();
        // Be aware: id inserted without any escaping!
        NodeList parents = (NodeList)xPath.evaluate("/class/question[@id='" + id + "']", doc, XPathConstants.NODESET);

        if (parents.getLength() < 1) {
            return null;
        } else if (parents.getLength() > 1) {
            // Huh, duplicates?
        }

        Element parent = (Element)parents.item(0);
        NodeList children = parent.getChildNodes();

        List<Element> answers = new ArrayList<Element>();

        for (int i = 0, max = children.getLength(); i < max; i++) {
            if (children.item(i).getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if (children.item(i).getNodeName().equals("ans") != true) {
                // Huh?
                continue;
            }

            answers.add((Element)children.item(i));
        }

        if (answers.size() <= 0) {
            return null;
        }

        int selection = (int)(Math.random() * answers.size());

        return answers.get(selection).getTextContent();
    }

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

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