【问题标题】:Java Xml Parsing :Distinguish two Xml Elements by missing tagJava Xml Parsing:通过缺少标签来区分两个 Xml 元素
【发布时间】:2014-07-11 08:51:43
【问题描述】:

从 Web 服务器请求中,我得到一个 XML 响应,其中包含我需要的数据。 它看起来像(摘录):

   <ctc:BasePrice>
  <cgc:PriceAmount amountCurrencyID="EUR">18.75</cbc:PriceAmount>
  <cgc:BaseQuantity quantityUnitCode="EA">1</cbc:BaseQuantity>
   </ctc:BasePrice>
  <ctc:BasePrice>
  <cgc:PriceAmount amountCurrencyID="EUR">18.25</cbc:PriceAmount>
  <cgc:BaseQuantity quantityUnitCode="EA">1</cbc:BaseQuantity>
  <cgc:MinimumQuantity quantityUnitCode="EA">3</cbc:MinimumQuantity>
  <ctc:BasePrice>

我需要的是第一个“PriceAmount”值,它可能是与第二个不同的价格。 但是我怎样才能确保检索到正确的,通过“告诉”解析器他应该采用不包含“MinimumQuantity”字段的元素并区分它们? 我在 Sax 等中阅读了很多内容,但可以找到如何为此实现“逻辑”的想法。 也许有人遇到了类似的问题。提前感谢每一个提示。

【问题讨论】:

    标签: java xml parsing


    【解决方案1】:

    您可以为此使用 xpath。表达式 "//*[local-name()='MinimumQuantity']/../*[local-name()='PriceAmount']" 应该返回你想要的。例如

    import java.io.ByteArrayInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class XpathParser {
        public static void main(String[] args) {
    
        try {
            String xml = "<root>"
                            + "<ctc:BasePrice>"
                                + "<cgc:PriceAmount amountCurrencyID=\"EUR\">18.75</cgc:PriceAmount>"
                                + "<cgc:BaseQuantity quantityUnitCode=\"EA\">1</cgc:BaseQuantity>"
                            + "</ctc:BasePrice>"
                            + "<ctc:BasePrice>"
                                + "<cgc:PriceAmount amountCurrencyID=\"EUR\">18.25</cgc:PriceAmount>"
                                + "<cgc:BaseQuantity quantityUnitCode=\"EA\">1</cgc:BaseQuantity>"
                                + "<cgc:MinimumQuantity quantityUnitCode=\"EA\">3</cgc:MinimumQuantity>"
                            + "</ctc:BasePrice>"
                        + "</root>";
    
            InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
    
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    
            DocumentBuilder builder =  builderFactory.newDocumentBuilder();
    
            Document xmlDocument = builder.parse(xmlStream);
    
            XPath xPath =  XPathFactory.newInstance().newXPath();
    
            String expression = "//*[local-name() = 'BasePrice' and not(descendant::*[local-name() = 'MinimumQuantity'])]/*[local-name()='PriceAmount']";
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }       
        }
    }
    

    Dom 解析器方式

    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    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.SAXException;
    
    
    public class DomParser{
    
        public static void main(String[] args) {
            try {
                String xml = "<root>"
                        + "<ctc:BasePrice>"
                            + "<cgc:PriceAmount amountCurrencyID=\"EUR\">18.75</cgc:PriceAmount>"
                            + "<cgc:BaseQuantity quantityUnitCode=\"EA\">1</cgc:BaseQuantity>"
                        + "</ctc:BasePrice>"
                        + "<ctc:BasePrice>"
                            + "<cgc:PriceAmount amountCurrencyID=\"EUR\">18.25</cgc:PriceAmount>"
                            + "<cgc:BaseQuantity quantityUnitCode=\"EA\">1</cgc:BaseQuantity>"
                            + "<cgc:MinimumQuantity quantityUnitCode=\"EA\">3</cgc:MinimumQuantity>"
                        + "</ctc:BasePrice>"
                        + "</root>";
    
                InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = builderFactory.newDocumentBuilder();
                Document xmlDocument = builder.parse(xmlStream);
                xmlDocument.getDocumentElement().normalize();
    
                NodeList nList = xmlDocument.getElementsByTagName("ctc:BasePrice");
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                        if(eElement.getElementsByTagName("cgc:MinimumQuantity").getLength() == 0){
                            System.out.println(eElement.getElementsByTagName("cgc:PriceAmount").item(0).getTextContent());
                        }
                    }
                }
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    
    }
    

    【讨论】:

    • 它为我返回了第二个价格,但我需要第一个。但我将不得不重新考虑一下。
    • @Jay.. 抱歉,我想反了。这就是为什么我选择所有具有最低数量的基本价格。我修改了我的答案。现在返回没有最小数量标签的基本价格。
    • 有没有办法通过使用 domparser 来做到这一点? (我解析出几个值)。但是谢谢:
    • 是的,当然可以通过 dom 解析器完成。您只需遍历子标签并检查 minimumQuatity..
    • 用 dom 解析器更新了我的答案。
    猜你喜欢
    • 2011-11-24
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多