Download presentation
Presentation is loading. Please wait.
1
46-929 Web Technologies1 Web Technologies Week Four Advanced DOM and Working with namespaces
2
46-929 Web Technologies2 Notes on XML Namespaces Namespace notes taken and adapted from “XML in a Nutshell” By Harold and Means Java examples adapted from “XML and Java” – course text Namespace specification is at: http://www.w3.org/TR/REC-xml-names/
3
46-929 Web Technologies3 Namespaces Primary purpose: To disambiguate element and attribute names. Implementation: Attach a prefix to an element or attribute name. Map the prefix to a URI. This need not be a real place. Default URI’s may also be provided for those elements with no prefix. The URI’s partition the elements and attributes into disjoint sets.
4
46-929 Web Technologies4 Namespaces Each prefix is associated with one URI. Names with prefixes associated with the same URI are in the same namespace. Elements and attributes in namespaces have names with exactly one colon. The text before the colon is called the prefix. The text after the colon is called the local part. The complete name, including the colon, is called the qualified name.
5
46-929 Web Technologies5 Namespaces Prefixes are bound to namespace URI’s by attaching an xmlns:prefix attribute to the the prefixed element or one of its ancestors For example: http://www.w3.org/TR/REC-rdf-syntax# associates the prefix rdf with the namespace URI shown. The name RDF is therefore an element from this namespace.
6
46-929 Web Technologies6 Namespaces Bindings have scope within the element in which they’re declared and its contents. http://www.w3.org/TR/REC-rdf-syntax# <!– within this element the prefix rdf is associated with the RDF namespace
7
46-929 Web Technologies7 Namespaces The default namespace Is set using the xmlns attribute (with no prefix) Applies only to elements not attributes … SomeTag and insideTag are both in the someURI namespace.
8
46-929 Web Technologies8 Namespaces If there is no default namespace is declared then tags without Prefixes are in no namespace at all. Not even the default one. The only way an attribute belongs to a namespace is if it has a declared prefix. http://www.w3.org/TR/REC-rdf-syntax# : The about attribute is in no namespace.
9
46-929 Web Technologies9 Declaring Namespaces xmlns:pre=“someURN” is fine xmlns:pre=“” is illegal xmlns=“someURN” is fine xmlns=“” legal and same as no namespace
10
46-929 Web Technologies10 Some Examples From The W3C Specification <!-- the 'price' element's namespace is http://ecommerce.org/schema --> 32.18
11
46-929 Web Technologies11 <!-- the 'taxClass' attribute's namespace is http://ecommerce.org/schema --> Baby food
12
46-929 Web Technologies12 Frobnostication Moved to here.
13
46-929 Web Technologies13 Cheaper by the Dozen 1568491379
14
46-929 Web Technologies14 <!-- elements are in the HTML namespace, in this case by default --> Frobnostication Moved to here.
15
46-929 Web Technologies15 Cheaper by the Dozen 1568491379
16
46-929 Web Technologies16 Cheaper by the Dozen 1568491379 <!-- make HTML the default namespace for some commentary --> This is a funny book!
17
46-929 Web Technologies17 Name Origin Description Huntsman Bath, UK Bitter Fuggles Wonderful hop, light alcohol, good summer beer Fragile; excessive variance pub to pub The default namespace can be set to the empty string. This has the same effect, within the scope of the declaration, of there being no default namespace.
18
46-929 Web Technologies18
19
46-929 Web Technologies19
20
46-929 Web Technologies20 Namespaces and Java // Exploring the NamespaceCorrector class in Chapter 4 of // XML and Java // Example 1 import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text;
21
46-929 Web Technologies21 public class NamespaceExplore { static final String NS = "http://www.andrew.cmu.edu/~mm6"; // the assigned namespace to the xml:lang attribute static final String XML_NS = "http://www.w3.org/XML/1998/namespace"; // the assigned namespace of the xmlns attribute static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/";
22
46-929 Web Technologies22 public static void main(String[] argv) throws Exception { DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setNamespaceAware(true); DocumentBuilder builder = dbfactory.newDocumentBuilder(); Document factory = builder.newDocument(); OutputFormat format = new OutputFormat("xml", "UTF-8", true); XMLSerializer serializer = new XMLSerializer(System.out, format); // build a top element within a namespace Element top = factory.createElementNS(NS, "mm6:GradeBook");
23
46-929 Web Technologies23 // define an xmlns attribute within this top element top.setAttributeNS(XMLNS_NS, "xmlns:mm6", NS); // define an xml:lang attribute within this top element top.setAttributeNS(XML_NS, "xml:lang", "en"); Element student = factory.createElementNS(NS,"mm6:Student"); top.appendChild(student); Text t = factory.createTextNode("87.5"); student.appendChild(t); serializer.serialize(top); System.out.println(""); }
24
46-929 Web Technologies24 D:\McCarthy\www\95-733\examples\chap04>java NamespaceExplore <mm6:GradeBook xml:lang="en" xmlns:mm6= "http://www.andrew.cmu.edu/~mm6"> 87.5 Output
25
46-929 Web Technologies25 Attributes and Namespaces // Exploring the NamespaceCorrector class in Chapter 4 of // XML and Java // Example 2 Looking at Attributes import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Attr;
26
46-929 Web Technologies26 public class NamespaceExplore2 { static final String NS = "http://www.andrew.cmu.edu/~mm6"; // the assigned namespace to the xml:lang attribute static final String XML_NS = "http://www.w3.org/XML/1998/namespace"; // the assigned namespace of the xmlns attribute static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/"; Same as before
27
46-929 Web Technologies27 public static void main(String[] argv) throws Exception { DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setNamespaceAware(true); DocumentBuilder builder = dbfactory.newDocumentBuilder(); Document factory = builder.newDocument(); OutputFormat format = new OutputFormat("xml", "UTF-8", true); XMLSerializer serializer = new XMLSerializer(System.out, format); Same as before
28
46-929 Web Technologies28 // build a top element within a namespace Element top = factory.createElementNS(NS, "mm6:GradeBook"); // define an xmlns attribute within this top element top.setAttributeNS(XMLNS_NS, "xmlns:mm6", NS); // define an xml:lang attribute withing this top element top.setAttributeNS(XML_NS, "xml:lang", "en"); // create a Student tag Element student = factory.createElementNS(NS,"mm6:Student"); // add a prefixed attribute to Student student.setAttributeNS(NS,"mm6:StudentID", "123-34-8765"); top.appendChild(student); We are creating attributes with namespaces.
29
46-929 Web Technologies29 Text t = factory.createTextNode("87.5"); student.appendChild(t); serializer.serialize(top); System.out.println(""); // display the attributes in the student tag showNamespaceOfAttributes(student); // display the attributes in the top tag showNamespaceOfAttributes(top); }
30
46-929 Web Technologies30 public static void showNamespaceOfAttributes(Element e) { System.out.println("Display attributes of " + e.getTagName()); NamedNodeMap map = e.getAttributes(); for (int i = 0; i < map.getLength(); i++) { Attr attr = (Attr)map.item(i); String prefix = attr.getPrefix(); String name = attr.getName(); String val = attr.getValue(); String uri = attr.getNamespaceURI(); System.out.println("Attribute ====>" + name); System.out.println(" prefix =" + prefix); System.out.println(" value = " + val); System.out.println(" NS URI = " + uri); }
31
46-929 Web Technologies31 Output D:\McCarthy\www\95-733\examples\chap04>java NamespaceExplore2 <mm6:GradeBook xml:lang="en“ xmlns:mm6="http://www.andrew.cmu.edu/~mm6"> 87.5 Display attributes of mm6:Student Attribute ====>mm6:StudentID prefix =mm6 value = 123-34-8765 NS URI = http://www.andrew.cmu.edu/~mm6
32
46-929 Web Technologies32 Display attributes of mm6:GradeBook Attribute ====>xml:lang prefix =xml value = en NS URI = http://www.w3.org/XML/1998/namespace Attribute ====>xmlns:mm6 prefix =xmlns value = http://www.andrew.cmu.edu/~mm6 NS URI = http://www.w3.org/2000/xmlns/
33
46-929 Web Technologies33 NCTest.java – XML and Java // NCTest.java Listing 4.2 XML and Java import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.w3c.dom.Element;
34
46-929 Web Technologies34 public class NCTest { static final String NS0 = "http://example.com/@"; static final String NS1 = "http://example.com/a"; static final String XML_NS = "http://www.w3.org/XML/1998/namespace"; static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/"; public static void main(String[] argv) throws Exception { DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setNamespaceAware(true); DocumentBuilder builder = dbfactory.newDocumentBuilder(); Document factory = builder.newDocument(); OutputFormat format = new OutputFormat("xml", "UTF-8", true); XMLSerializer serializer = new XMLSerializer(System.out, format);
35
46-929 Web Technologies35 Element top = factory.createElementNS(null, "Address"); top.setAttributeNS(XMLNS_NS, "xmlns:p", NS0); // Add an element that has the namespace and no prefix. Element el1 = factory.createElementNS(NS1, "Zip"); // el1 has an attribute of which namespace is // the same as el1. el1.setAttributeNS(NS1, "p:id", ""); el1.appendChild(factory.createElementNS(null, "Zip2")); top.appendChild(el1); // Add an element that has the namespace and prefix. Element el2 = factory.createElementNS(NS1, "p:State"); // add an attribute to el2 -- code deleted -- no harm mistake in book el2.setAttributeNS(XML_NS, "xml:lang", "en"); top.appendChild(el2);
36
46-929 Web Technologies36 Element el3 = factory.createElementNS(NS0, "p:City"); top.appendChild(el3); // Prints the tree before correction. serializer.serialize(top); System.out.println(""); // Correct NamespaceCorrector.correct(top); // Prints the tree after correction. serializer.reset(); serializer.serialize(top); System.out.println(""); What does the output document look like? Now, what does the output document look like?
37
46-929 Web Technologies37 // Another test: // p:Country and p:iso2 have the same prefix but // different namespaces. Element el4 = factory.createElementNS(NS0, "p:Country"); el4.setAttributeNS(NS1, "p:iso2", "ja"); // This should throw an exception. NamespaceCorrector.correct(el4); } What does this document look like and why can’t it be repaired?
38
46-929 Web Technologies38 D:\McCarthy\www\95-733\examples\chap04>javac NCTest.java D:\McCarthy\www\95-733\examples\chap04>java NCTest This is not as the author intended.
39
46-929 Web Technologies39 <Zip p:id="" xmlns="http://example.com/a" xmlns:p="http://example.com/a"> Corrected document.
40
46-929 Web Technologies40 Exception in thread "main" org.w3c.dom.DOMException: Namespace inconsistence at NamespaceCorrector.set(NamespaceCorrector.java:89) at NamespaceCorrector.correctElement(NamespaceCorrector.java:78) at NamespaceCorrector.correct(NamespaceCorrector.java:26) at NCTest.main(NCTest.java:67) Too bad to fix.
41
46-929 Web Technologies41 NamespaceCorrector.java // NamespaceCorrector.java import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap;
42
46-929 Web Technologies42 /** * Add required namespace declarations. */ public class NamespaceCorrector { private static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/"; private NamespaceCorrector() { }
43
46-929 Web Technologies43 /** @param node The top node of target nodes */ public static void correct(Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: correctElement((Element)node); // Fall down case Node.DOCUMENT_NODE: case Node.DOCUMENT_FRAGMENT_NODE: case Node.ENTITY_REFERENCE_NODE: for (Node ch = node.getFirstChild(); ch != null; ch = ch.getNextSibling()) { correct(ch); } break; }
44
46-929 Web Technologies44 /** * Check whether the prefixes and the namespaces of el and * its attributes are declared or not. * if not, add a namespace declaration to el. */ private static void correctElement(Element el) { // Check el. String prefix = el.getPrefix(); String current = el.getNamespaceURI(); String declared = howDeclared(el, prefix);
45
46-929 Web Technologies45 if (prefix == null) { if (current == null && declared == null) { // ok } else if (current == null || declared == null) { set(el, prefix, current == null ? "" : current); } else if (!current.equals(declared)) { set(el, prefix, current); } } else { if (current == null) throw new DOMException( DOMException.NAMESPACE_ERR, el.getNodeName() +" has no namespace"); if (declared == null || !current.equals(declared)) set(el, prefix, current); }
46
46-929 Web Technologies46 // Check attributes of el. NamedNodeMap map = el.getAttributes(); for (int i = 0; i < map.getLength(); i++) { Attr attr = (Attr)map.item(i); prefix = attr.getPrefix(); if (prefix == null || prefix.equals("xml") || prefix.equals("xmlns")) continue; current = attr.getNamespaceURI(); declared = howDeclared(el, prefix); if (declared == null || !current.equals(declared)) { set(el, prefix, current); i = -1; // map has changed. // So restart the loop. }
47
46-929 Web Technologies47 private static void set(Element el, String prefix, String ns) { String qname = prefix == null ? "xmlns" : "xmlns:"+prefix; if (el.getAttributeNode(qname) != null) throw new DOMException(DOMException.NAMESPACE_ERR, "Namespace inconsistence"); el.setAttributeNS(XMLNS_NS, qname, ns); }
48
46-929 Web Technologies48 /** * Search context and ancestors for declaration * of prefix. * @param prefix Prefix, or null for default ns. */ private static String howDeclared(Element context, String prefix) { String qname = prefix == null ? "xmlns" : "xmlns:"+prefix;
49
46-929 Web Technologies49 for (Node node = context; node != null; node = node.getParentNode()) { if (node.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element)node).getAttributeNode(qname); if (attr != null) { if (prefix == null && attr.getNodeValue().equals("")) return null; else return attr.getNodeValue(); } return null; }
50
46-929 Web Technologies50 Homework Trace the NamespaceCorrector.java program for the following cases: Case 1: An element has a namespace but no prefix. An ancestor of the element has a default namespace with the same namespace value. Case 2: An element has a namespace but no prefix and no default namespace exists.
51
46-929 Web Technologies51 Case 3. An element has a namespace but no prefix and an ancestor has a different default namespace. Case 4. An element has a namespace but no prefix and this element declares a different default namespace. Case 5. An element has a namespace and a prefix that points to a different namespace.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.