【问题标题】:Reading CDATA value in comments of xml java在xml java的注释中读取CDATA值
【发布时间】:2016-09-20 22:03:10
【问题描述】:

我有以下 xml。

<add-item item-descriptor="sku" id="235957441">
    <set-property name="skuType"><![CDATA[NORMAL]]></set-property>
    <set-property name="isPartOfClearancePriceList"><![CDATA[false]]></set-property>
    <set-property name="size"><![CDATA[Single set]]></set-property>
    <!-- rdonly   <set-property name="prices"><![CDATA[then2price=-1.0,clearanceprice=-1.0,then1price=-1.0,extravaganzaprice=-1.0,wasprice=-1.0,nowprice=10.0]]></set-property>  -->
    <!-- rdonly  derived   <set-property name="dissectionName"><![CDATA[DUVETCOVERCOL2]]></set-property>  -->
  </add-item>

在上面的xml中,我必须使用java代码读取prices注释的then2priceclearancepricethen1price的值。

我设法读取了 cmets,但无法读取 cmets 的 CDATA

Java 代码:

        NodeList nl = doc.getDocumentElement().getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeType() == Element.COMMENT_NODE) {
                Comment comment = (Comment) nl.item(i);
                // System.out.println(comment.getNodeValue());
                Node child = nl.item(i);
                if(child instanceof CharacterData){
                    CharacterData cd = (CharacterData) child;
                    System.out.println(cd.getNodeValue());
                }
            }

上面的代码不是打印 CDATA 中的值,而是打印完整的注释。

我只需要输出中的then2price=-1.0,clearanceprice=-1.0,then1price=-1.0,extravaganzaprice=-1.0,wasprice=-1.0,nowprice=10.0

非常感谢。

【问题讨论】:

    标签: java xml unmarshalling cdata


    【解决方案1】:
    String xmlStr = comment.getNodeValue();
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
    
    if (doc.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(doc.getFirstChild().getTextContent());
    }
    

    它将按预期为您获取 CDATA 中的数据。

    注意:当然,您还需要为 cmets 设置 xml 格式。目前我确实看到你有 'rdonly' 和 'rdonly 派生的。请删除它们并调用上述方法。

    【讨论】:

      猜你喜欢
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多