问题
I'm parsing XML using pugi xml, which is not a namespace-aware parser (see Using Boost to read and write XML files). I'm trying to figure out how much of an issue this might be, but the problem is I don't 100% understand what XML namespaces are used for.
Here is an example of some XML (that I created) that would be problematic:
<Results>
<Documents xmlns:active="...">
<Document>...</Document>
</Documents>
<Documents xmlns:archived="...">
<Document>...</Document>
<Document>...</Document>
<Document>...</Document>
<Document>...</Document>
</Documents>
</Results>
Given an XPath expression like /Results/Documents/Document
, all pugi could do for me is extract all <Document>
elements -- I'd lose the active/archived information. However, I'm not sure if I'd ever encounter this type of namespace use in the real world. It seems like in this situation it would be better use an attribute to get across the active/archived information. Can someone help me better understand the situations namespaces are used in so I can get a better idea for what I'd be losing out on by sticking with pugi xml?
回答1:
Although default namespace declarations (e.g. xmlns="http://www.example.com"
) and namespace prefix declarations (e.g. xmlns:e="http://www.example.com"
) resemble attributes, XML namespaces serve a completely different purpose than XML attributes.
The purpose of XML namespaces is to allow independently developed XML vocabularies to be combined in a single XML document while providing both a way for names to be associated with a vocabulary and a way to avoiding naming collisions between vocabularies.
The purpose of XML attributes is to represent data or metadata. (See XML attribute vs XML element.)
Whether the degree of support for XML namespaces by any given XML or XPath processor is acceptable to you will depend upon the both the particulars of what's (not) supported as well as the particulars of your needs. Do note, however, that noncompliance has a serious disadvantage: You've already witnessed surprising disagreement between compliant and noncompliant processors where the same XPath returned completely different results for the same XML document. Interoperability prefers compliance.
来源:https://stackoverflow.com/questions/40814406/namespace-usage-in-xml