有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么没有明确指定名称空间的XML属性不能被分配到默认名称空间

我正在分析此XML文档:

<?xml version='1.0' encoding='UTF-8'?>
<team xmlns='http://www.example.com/default' xmlns:ns1='http://www.example.com/ns1'>
    <ns1:coach ns1:coachAttr="ABC"/>
    <player playerAttr="XYZ"/>
</team>

我希望playerplayAttr位于http://www.example.com/default命名空间中,而coachcoachAttr位于http://www.example.com/ns1命名空间中

结果是playerAttr根本没有名称空间。代码如下:

String xml="...";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));

Element team = doc.getDocumentElement();
Element player = (Element) team.getChildNodes().item(...);
Element coach = (Element) team.getChildNodes().item(...);
Attr playerAttr = (Attr) player.getAttributes().item(...);
Attr coachAttr = (Attr) coach.getAttributes().item(...);

System.out.println("coach: Name=" + coach.getLocalName() + " NS=" + coach.getNamespaceURI());
System.out.println("coachAttr: Name=" + coachAttr.getLocalName() + " NS=" + coachAttr.getNamespaceURI());
System.out.println("player: Name=" + player.getLocalName() + " NS=" + player.getNamespaceURI());
System.out.println("playerAttr: Name=" + playerAttr.getLocalName() + " NS=" + playerAttr.getNamespaceURI());

这个打印出4行。前三个对我来说很有意义。我不理解最后一行,其中NS为null

coach: Name=coach NS=http://www.example.com/ns1
coachAttr: Name=coachAttr NS=http://www.example.com/ns1
player: Name=player NS=http://www.example.com/default
playerAttr: Name=playerAttr NS=null

为什么playerAttr会受到不同的对待?这是某种规格吗?项没有名称空间是什么意思


共 (2) 个答案

  1. # 1 楼答案

    每个XML解析器的行为都是这样的。既然你的问题是“为什么”,我想这对于大多数实际目的来说只是一种更简单的方法

    更多详情请点击此处:

    https://stackoverflow.com/a/3313538/80911

  2. # 2 楼答案

    你说的“为什么”到底是什么意思。你的意思是“在哪里指定了这种行为?”,或者“设计师对这个决定给出了什么理由?”或者“这样做有什么好处?”

    (顺便说一下,这些问题都不适合StackOverflow…)

    事实上,在这一点上并没有普遍的共识。DOM、XPath和大多数其他API都是这样做的,但XML名称空间规范本身并不强制要求这样做,它说:

    Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.

    我听过很多关于这意味着什么的理论,但是没有一个理论能够很好地转化为具体的API

    实际上,您需要查看正在使用的API的规范,在本例中是DOM。(StackOverflow上99%的Java/XML用户似乎使用DOM,我觉得这非常令人沮丧,因为有更好的替代方案,如JDOM2和XOM。)