java 在java中从XML获取子节点的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13591298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:19:36  来源:igfitidea点击:

Getting value of child node from XML in java

javaxmldom

提问by yogsma

My xml file looks like this

我的 xml 文件看起来像这样

 <InNetworkCostSharing>
                <FamilyAnnualDeductibleAmount>
                    <Amount>6000</Amount>
                </FamilyAnnualDeductibleAmount>
                <IndividualAnnualDeductibleAmount>
                    <NotApplicable>Not Applicable</NotApplicable>
                </IndividualAnnualDeductibleAmount>
                <PCPCopayAmount>
                    <CoveredAmount>0</CoveredAmount>
                </PCPCopayAmount>
                <CoinsuranceRate>
                    <CoveredPercent>0</CoveredPercent>
                </CoinsuranceRate>
                <FamilyAnnualOOPLimitAmount>
                    <Amount>6000</Amount>
                </FamilyAnnualOOPLimitAmount>
                <IndividualAnnualOOPLimitAmount>
                    <NotApplicable>Not Applicable</NotApplicable>
                </IndividualAnnualOOPLimitAmount>
 </InNetworkCostSharing>

I am trying to get Amount value from <FamilyAnnualDeductibleAmount>and also from <FamilyAnnualOOPLimitAmount>. How do i get those values in java?

我正在尝试<FamilyAnnualDeductibleAmount><FamilyAnnualOOPLimitAmount>. 我如何在java中获取这些值?

采纳答案by yogsma

I think I found the solution with this question from stackoverflow

我想我从stackoverflow找到了这个问题的解决方案

Getting XML Node text value with Java DOM

使用 Java DOM 获取 XML 节点文本值

回答by Alex

You may use two XPath queries /InNetworkCostSharing/FamilyAnnualDeductibleAmountand InNetworkCostSharing/FamilyAnnualOOPLimitAmountor just get the node InNetworkCostSharingand retrieve the values of its two direct children.

您可以使用两个 XPath 查询/InNetworkCostSharing/FamilyAnnualDeductibleAmountInNetworkCostSharing/FamilyAnnualOOPLimitAmount或者只是获取节点InNetworkCostSharing并检索其两个直接子节点的值。

Solution using XPath:

使用 XPath 的解决方案:

// load the XML as String into a DOM Document object
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream("YOUR XML".getBytes());
Document doc = docBuilder.parse(bis);

// XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/InNetworkCostSharing/FamilyAnnualDeductibleAmount/text()");
String familyAnnualDeductibleAmount = (String)expr.evaluate(doc, XPathConstants.STRING);

回答by Yogendra Singh

Try something like this(use getElementsByTagName to get the parent nodes and then get the value be reaching out to child node):

尝试这样的事情(使用 getElementsByTagName 获取父节点,然后获取值到达子节点):

   File xmlFile = new File("NetworkCost.xml");
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(xmlFile );
   doc.getDocumentElement().normalize();

   NodeList nList = doc.getElementsByTagName("FamilyAnnualDeductibleAmount");
   String familyDedAmount = nList.item(0).getChildNodes().item(0).getTextContent();

   nList = doc.getElementsByTagName("FamilyAnnualOOPLimitAmount");
   String familyAnnualAmount = 
                            nList.item(0).getChildNodes().item(0).getTextContent();

回答by Evgeniy Dorofeev

StAX based solution:

基于 StAX 的解决方案:

    XMLInputFactory f = XMLInputFactory.newInstance();
    XMLStreamReader rdr = f.createXMLStreamReader(new FileReader("test.xml"));
    while (rdr.hasNext()) {
        if (rdr.next() == XMLStreamConstants.START_ELEMENT) {
            if (rdr.getLocalName().equals("FamilyAnnualDeductibleAmount")) {
                rdr.nextTag();
                int familyAnnualDeductibleAmount = Integer.parseInt(rdr.getElementText());
                System.out.println("familyAnnualDeductibleAmount = " + familyAnnualDeductibleAmount);
            } else if (rdr.getLocalName().equals("FamilyAnnualOOPLimitAmount")) {
                rdr.nextTag();
                int familyAnnualOOPLimitAmount = Integer.parseInt(rdr.getElementText());
                System.out.println("FamilyAnnualOOPLimitAmount = " + familyAnnualOOPLimitAmount);
            }
        }
    }
    rdr.close();

Note that StAX is especially good for cases like yours, it skips all unnecessary elements reading only the ones you need

请注意,StAX 特别适合像您这样的情况,它会跳过所有不必要的元素,只读取您需要的元素