【问题标题】:Get the name of namespace xmlns from xsd file through XmlSlurper/XmlParser通过 XmlSlurper/XmlParser 从 xsd 文件中获取命名空间 xmlns 的名称
【发布时间】:2015-05-06 15:24:20
【问题描述】:

我正在尝试通过 Groovy 获取 xml(xsd) 文件的命名空间。 XmlParsers 返回的 Node 和 XmlSlurper 的 GPathResult 似乎忽略了命名空间定义。

举个例子:

 <?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com"
    elementFormDefault="qualified">

试图通过获取rootNode的属性

rootNode.attributes()

将只检索:

targetNamespace:http://www.w3schools.com
elementFormDefault:qualified

并省略 xml:nsxmlns 定义。 GPathResult 的@ 属性中包含相同的结果。

似乎这与 Node 类实现无关,并且依赖于使用的 XmlParsers。

那么应该如何实现 XmlParser 以将这些属性包含在节点中,以及将其留在 Groovy 之外的任何原因?

【问题讨论】:

    标签: groovy xsd xml-parsing


    【解决方案1】:

    使用XmlSlurper constructor 的不同变体:

    def xml = """<?xml version="1.0"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com"
        elementFormDefault="qualified">
    </xs:schema>
    """
    
    assert new XmlSlurper(false, false, false).parseText(xml).attributes() == [
        'xmlns:xs':'http://www.w3.org/2001/XMLSchema', 
        'targetNamespace':'http://www.w3schools.com', 
        'xmlns':'http://www.w3schools.com', 
        'elementFormDefault':'qualified'
    ]
    

    【讨论】:

    • 哦,我没有检查构造函数。谢谢。
    猜你喜欢
    • 2016-01-29
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多