代码之家  ›  专栏  ›  技术社区  ›  user1523153

如何在没有GPath/节点名的情况下提取CDATA

  •  1
  • user1523153  · 技术社区  · 6 年前

    我正在尝试从XML中提取CDATA内容,而不使用GPath(或)节点名。简而言之,我想从XML中查找和检索包含CDATA的innerText部分。

    我的XML看起来像:

    def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <root>
        <Test1>This node contains some innerText. Ignore This.</Test1>
        <Test2><![CDATA[this is the CDATA section i want to retrieve]]></Test2>
    </root>'''
    

    从上面的XML中,我想单独获取CDATA内容,而不使用其节点名“Test2”的引用。因为节点名在我的场景中并不总是相同的。

    还请注意,XML可以在其他几个节点中包含innerText(Test1)。我不想找回那个。我只需要整个XML中的CDATA内容。

    我想要下面这样的东西(下面的代码是不正确的)

    def parsedXML = new xmlSlurper().parseText(xml)
    def cdataContent = parsedXML.depthFirst().findAll { it.text().startsWith('<![CDATA')}  
    

    我的输出应该是:

    this is the CDATA section i want to retrieve
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   tim_yates    6 年前

    正如@daggett所说的,您不能用Groovy slurper或解析器来实现这一点,但是下拉并使用java类来获得它也不是太糟糕。

    注意,您必须将CDATA的属性设置为可见,因为在默认情况下,它只被视为字符。

    代码如下:

    import javax.xml.stream.*
    
    def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <root>
        <Test1>This node contains some innerText. Ignore This.</Test1>
        <Test2><![CDATA[this is the CDATA section i want to retrieve]]></Test2>
    </root>'''
    
    def factory = XMLInputFactory.newInstance()
    factory.setProperty('http://java.sun.com/xml/stream/properties/report-cdata-event', true)
    
    def reader = factory.createXMLStreamReader(new StringReader(xml))
    while (reader.hasNext()) {
        if (reader.eventType in [XMLStreamConstants.CDATA]) {
            println reader.text
        }
        reader.next()
    }
    

    会打印出来的 this is the CDATA section i want to retrieve

        2
  •  1
  •   Gaurav Khurana    6 年前

    考虑到xml中只有一个CDATA 分裂 你能帮我吗

    def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <root>
    <Test1>This node contains some innerText. Ignore This.</Test1>
    <Test2><![CDATA[this is the CDATA section i want to retrieve]]></Test2>
     </root>'''
    
     log.info xml.split("<!\\[CDATA\\[")[1].split("]]")[0]
    

    xml.split("<!\\[CDATA\\[")[1]
    

    一旦我们得到了那部分,我们再次进行了拆分,然后得到了在这个模式之前的那部分

    .split("]]")[0] 
    

    enter image description here