如何在Java中使用DOM获取目标命名空间及其前缀?

时间:2017-10-27 13:29:43

标签: java xml dom element

假设我有一个这样的XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema 
     targetNamespace="http://www.sample.com" 
     xmlns:sa="http://www.sample.com" 
     xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="name" type="sa:NameType"/>   
    <xs:simpleType name="NameType">
        <xs:restriction base="xs:string">
            <xs:maxLength value="100"/>
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

假设我有这个模式的DOM文档,可能通过这样做:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = = documentBuilder.parse(uriToSchema.toString());

如何获取目标命名空间(http://www.sample.com)及其关联的前缀(sa)?

我以为我可以这样做:

String namespace = ((Element) document.getDocumentElement()).getNamespaceURI());
String prefix = ((Element) document.getDocumentElement()).getPrefix());

但是它获得了XML Schema命名空间(http://www.w3.org/2001/XMLSchema)及其关联的前缀(xs)。

2 个答案:

答案 0 :(得分:0)

@Yogi的回答指出了我正确的方向。这是解决方案:

NamedNodeMap map = ((Element) document.getDocumentElement()).getAttributes();
String namespace = map.getNamedItem("targetNamespace").getNodeValue();
String prefix = "";
for (int i = 0; i < map.getLength(); i++)
{
   Attr attr = (Attr) map.item(i);
   if (attr.getValue().equals(namespace) && !attr.getName().equals("targetNamespace"))
   {
      prefix = attr.getName().split(":")[1];
      break;
   }
}
System.out.println("ns: " + namespace);
System.out.println("pr: " + prefix);

答案 1 :(得分:-1)

您需要迭代文档元素的所有属性,如:

Path path = Paths.get(Typedetection.class.getClassLoader()
                 .getResource("data.xml").toURI());   

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(path.toFile());

        Element documentElement = (Element) document.getDocumentElement();
        String namespace = documentElement.getNamespaceURI();
        String prefix = documentElement.getPrefix();
        System.out.println("Namespace:"+namespace);
        System.out.println("Prefix:"+prefix);

        NamedNodeMap map = documentElement.getAttributes();
        for (int iattr=0; iattr<map.getLength(); iattr++) {
           Attr attr = (Attr)map.item(iattr);
           if (attr.getNamespaceURI() != null) {
              System.out.println("Attr " + attr.getName() + " -  " + attr.getNamespaceURI());
           }
        }
    }