180 likes | 483 Views
Современные языки и технологии программирования. Использование XML. Пространства имен XML. <famous:person xmlns:famous=“http://mysite.com/famous”> < famous: name famous:first=“Alan” famous:last=“Turing”/ >
E N D
Современные языки и технологии программирования Использование XML
Пространства имен XML <famous:person xmlns:famous=“http://mysite.com/famous”> <famous:name famous:first=“Alan” famous:last=“Turing”/> <famous:profession>computer scientist</famous:profession> <famous:profession>mathematician</famous:profession> <famous:profession>cryptographer</famous:profession> <famous:biography> <![CDATA[ <Long story> ]]> </famous:biography> </famous:person>
Пространство имен по умолчанию для элемента <person xmlns=“http://mysite.com/famous”> <name first=“Alan” last=“Turing”/> <profession>computer scientist</profession> <profession>mathematician</profession> <profession>cryptographer</profession> <biography> <![CDATA[ <Long story> ]]> </biography> </person>
Схема документа (XSD) • Формальное описание валидного XML документа • Более мощное и выразительное средство по сравнению с DTD • Может определять комплексные ограничения на элементы и их атрибуты • Для валидации документа может использоваться несколько схем • Формат XSD сам по себе имеет структуру XML
Схема XML - возможности • Вложенность элементов • Ограничения на присутствие элементов • Разрешенные атрибуты • Типы атрибутов и значения по умолчанию • Простые и сложные типы данных • Наследование типов • Точные ограничения на количество вложенных дочерних элементов • Учитываются пространства имен
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://mysite.com/famous" xmlns:tns="http://mysite.com/famous" elementFormDefault="qualified"> <xsd:element name="person"> <xsd:complexType> <xsd:sequence> <xsd:element name="name"> <xsd:complexType> <xsd:attribute name="first" type="xsd:string" use="required"/> <xsd:attribute name="last" type="xsd:string" use="required"/> <xsd:attribute name="some_id" type="xsd:ID" use="required"/> </xsd:complexType> </xsd:element> <xsd:element name="profession" minOccurs="0" maxOccurs="unbounded" type="xsd:string"/> <xsd:element name="biography" minOccurs="0"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="another_id" type="xsd:ID"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> <xsd:attribute name="born" type="xsd:date" use="required"/> <xsd:attribute name="died" type="xsd:date"/> </xsd:complexType> </xsd:element> </xsd:schema>
Проверка XML по схеме SAXParserFactory f = SAXParserFactory.newInstance(); f.setValidating(false); f.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema s = schemaFactory.newSchema(new File("src/famous.xsd“)); f.setSchema(s); SAXParser p = f.newSAXParser(); p.parse(new FileInputStream(args[0]) , new MyContentHandler());
XSL, XSLT, XPath • Extensible Stylesheet Language (XSL): • XSL-FO (Formatted Objects) - стандарт описывающий форматирование и представление объектов • XSLT трансформация XML – язык, основанный на правилах («если-то») • XPath – средство определения пути и выборки XML докуентов, используемое в XSL/XSLT, XPointer
XPath • Выражение для выборки узлов XML: • Корневого элемента ( “/” ) • Определенного элемента (“/name”) • Текста ( “text()” ) • Атрибута ( “/name@first” ) • Комментария ( “comment()” ) • Инструкции обработки (“processing_instruction()”) • Пространства имен( “famous:profession”)
Примеры выражений XPath “./name” “profession” “/person” “.//profession” “name/@first” “name[@last=‘Turing’]” “famous:biography” • “.” – текущий узел (не путать с элементом!!!) • “..” – родительский узел • [] – предикат • “some_function()” – функция над текущим узлом • “/some/path” – абсолютный путь • “some/path” – относительный путь от текущего • “@*” – любой узел - атрибут • “*” – любой узел – элемент • “node()” – любой узел
XSLT - трансформация • Определяет набор правил преобразования XML документа • Все правила применяются рекурсивно • Выбор правила осуществляется на основе XPath либо явным вызовом по имени • Может быть оптимизирован под вывод текста, HTML, XML • Поддерживает условные выражения
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" indent="yes"/> <xsl:template match="/person"> <html> <head> <title><xsl:value-of select="name/@first"/></title> </head> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="name[@last='Turing']"> <b><xsl:value-of select="@first"/> <xsl:text> </xsl:text><xsl:value-of select="@last"/></b> <br/> </xsl:template> <xsl:template match="profession"> <i><xsl:value-of select="text()"/></i><br/> </xsl:template> <xsl:template match="biography"/> </xsl:stylesheet>
Использование XSLT DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = f.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new FileReader(args[0]))); StreamSource style = new StreamSource(new File("src/famoushtml.xsl")); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(style); t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("res.html")));
XLink – простая ссылка <novel xmlns:xlink= "http://www.w3.org/1999/xlink" xlink:type = "simple" xlink:href = "ftp://archive.org/pub/etext/etext93/wizoz10.txt"> <title> The Wonderful Wizard of Oz </title> <author> L. Frank Baum </author> <year>1900</year> </novel> • XPointer – ссылка вместе с XPath <first xlink:type="simple" xlink:href= “slides.xml#xpointer(//slide[position( )=1])"> Start </first>
XLink – сложная ссылка <novel xlink:type = "extended"> <title>The Wonderful Wizard of Oz</title> <author>L. Frank Baum</author> <year>1900</year> <edition xlink:type="locator" xlink:href="urn:isbn:0688069444" xlink:label="ISBN0688069444"/> <edition xlink:type="locator" xlink:href="urn:isbn:0192839306" xlink:label="ISBN0192839306"/> <edition xlink:type="locator" xlink:href="urn:isbn:0700609857" xlink:label="ISBN0700609857"/> </novel>
JAXB – XML binding <xsd:complexType name="ISPAEntity"> <xsd:sequence> <xsd:element name="account" type="xsd:string"/> <xsd:element name="info" type="xsd:string"/> <xsd:element name="phone" type="xsd:string"/> </xsd:sequence> </xsd:complexType> XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ISPAEntity", propOrder = { "account", "info", "phone" }) public class ISPAEntity { @XmlElement(required = true) protected Long account; @XmlElement(required = true) protected String info; @XmlElement(required = true) protected String phone; }
Использование JAXB • Генерация кода xjc -p com.mypackage -d gen/ myschema.xsd • Использование JaxbContext jc = JAXBContext.newInstance( “com.mypackage"); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<?> poElement = (JAXBElement<?>)u.unmarshal(new StringReader(source)); MyClass response=(MyClass)poElement.getValue();
Задача • Определить схему XSD • Валидировать на основе схемы 3 • Определить стиль XSL для трансформации в HTML • Трансформировать в HTML • Расширить схему XSD декларациями JAXB • Сгенерировать XJC классы-обертки для JAXB • Попробовать работать с документом через объекты JAXB