Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- File myxml = new File("test.xml");
- try {
- //dom parse
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(myxml);
- Element root = doc.getDocumentElement();
- System.out.println(root.getTagName());
- //xpath
- System.out.println("xpath:");
- XPathFactory xpf = XPathFactory.newInstance();
- XPath xp = xpf.newXPath();
- XPathExpression xpe = xp.compile("/Address/Town[@id=456 ]/text()|" +
- "/Address/Town[last()]/attribute::myattr");
- Object res = xpe.evaluate(doc, XPathConstants.NODESET);
- NodeList nodes = (NodeList) res;
- for (int i = 0; i < nodes.getLength(); i++) {
- System.out.println("node:" + nodes.item(i).getNodeName() + ": " + nodes.item(i).getNodeValue());
- }
- //xsd validation
- SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
- File schemaLoc = new File("testschema.xsd");
- Schema sc = sf.newSchema(schemaLoc);
- Validator v = sc.newValidator();
- Source src = new StreamSource(myxml);
- try {
- v.validate(src);
- System.out.println("is valid");
- } catch (SAXException sax) {
- System.out.println("invalid");
- }
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- }
- <?xml version="1.0" encoding="utf-8"?>
- <Address>
- <Recipient>Mr. Walter C. Brown</Recipient>
- <House>49</House>
- <Street>Featherstone Street</Street>
- <Town id="123">LONDON</Town>
- <Town id="456">MOSCOW</Town>
- <Town id="789" myattr="nya">TOKYO</Town>
- <PostCode>EC1Y 8SY</PostCode>
- <Country>UK</Country>
- </Address>
- <?xml version="1.0" encoding="utf-8"?>
- <xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
- <xs:element name="Address">
- <xs:complexType>
- <xs:sequence>
- <xs:element name="Recipient" type="xs:string" />
- <xs:element name="House" type="xs:string" />
- <xs:element name="Street" type="xs:string" />
- <xs:element name="Town" type="xs:string" />
- <xs:element name="County" type="xs:string" minOccurs="0" />
- <xs:element name="PostCode" type="xs:string" />
- <xs:element name="Country">
- <xs:simpleType>
- <xs:restriction base="xs:string">
- <xs:enumeration value="FR" />
- <xs:enumeration value="DE" />
- <xs:enumeration value="ES" />
- <xs:enumeration value="UK" />
- <xs:enumeration value="US" />
- </xs:restriction>
- </xs:simpleType>
- </xs:element>
- </xs:sequence>
- </xs:complexType>
- </xs:element>
- </xs:schema>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement