XMLを使用した春ブーツDOM4J XStreamの操作

XMLは依然として、マイクロチャネルインタフェース使用XML定義されたメッセージのように、より重要な位置を占めます。この章では、XMLに重点を置いて作成、編集、検索、変換、理解することができ、この章では、dom4jのを使用することである、XStreamのは、最も広く開発者の間で使用されています。この章では、オペレーショナルXMLライブラリのすべてのビットです。

0 DOM4J XStreamのブリーフ

XMLワードが動作パフォーマンスライブラリに焦点を当てDOM4J、Xstreamのは、オブジェクト間の変換に焦点を当てています。

DOM4J

DOM4Jは、XPath、XMLスキーマ、大規模な文書やイベントベースのドキュメント処理の流れを支援します。

DOM4JはDOM4J-API関数と標準の基本となるDOM-APIによって並列にアクセスすることができる文書表現のためのビルドオプションを提供します。

上記の野心的な目標を達成するために、DOM4Jはインターフェイスと抽象基底クラスと広くJDKコレクションクラスで使用される方法を使用します。

DOM4Jは、上記の利点を取るために大規模なAPI、DOM4Jより多くの柔軟性を持っているので、パフォーマンスは申し分ないです。

HibernateのXML設定ファイルで有名な日-JAXM、の卓越した評判がDOM4Jを使用して解析されます。

XStreamの

XStreamのベースOXMapping技術は、他のヘルパークラスやマップファイルを注意していない、またはあなたが休止状態のORMフレームワークを使用した場合、ここで理解することは困難ではないOXMようMyBatisの。

配列は、XMLにXStreamのJavaBeanのである移動やJavaBeanのXML、面倒ではないようなXMLシリアル化をデシリアライズしてもよいです。

XStreamのJavaBeanはシリアライズまたは、JSON使いやすい非直列化することができます。

簡潔なAPIと組み合わせてのマッピングファイルとXML解析、高性能、低メモリフットプリントを押しxmlpull使用して基礎となるモデルは、基本的には毎分事を始めませんます。

XStreamのは、変換戦略のタイプをカスタマイズすることができ、詳細なエラー診断で、あなたはすぐに問題を特定することができます。

1つの新しい春のブートMavenのサンプルプロジェクト

注意:IDEAはのための開発ツールです

  1. ファイル>新規>プロジェクト、以下の図を選択Spring Initializrして、[次へ]をクリックします次
  2. フィルGroupId(パッケージ名)、 Artifactプロジェクト名)にすることができます。次のクリック
    のgroupId = com.fishpro
    たartifactId = xmldom4jを
  3. 選択は異なりSpring Web Starter、フロントダニを。
  4. プロジェクト名が設定されていますspring-boot-study-xmldom4j

図2は、依存ポンポンを紹介します

  • Java用のdom4j-1.6.1のサポート1.4+
  • Java用のdom4j-2.0.2のサポート5+
  • Java用のdom4j-2.1.1のサポート8+

mvnrepositoryのみ1.6.1 1.6.1を使用します

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jaxen/jaxen xpath解析的时候需要引入 jaxen包 否则会报错 java.lang.NoClassDefFoundError: org/jaxen/JaxenException-->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream 支持xml转bean -->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.11.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

コード例3 DOM4J

3.1リモートのXMLを開きます

 /**
     * 解析远程 XML 文件
     * @return Document xml 文档
     * */
    public static Document parse(URL url) throws DocumentException{
        SAXReader reader = new SAXReader();
        Document document =reader.read(url);
        return document;
    }

3.2 XML文書を作成します

/**
     * 创建一个 xml 文档
     * */
    public static Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");

        Element author1 = root.addElement("author")
                .addAttribute("name", "James")
                .addAttribute("location", "UK")
                .addText("James Strachan");

        Element author2 = root.addElement("author")
                .addAttribute("name", "Bob")
                .addAttribute("location", "US")
                .addText("Bob McWhirter");

        return document;
    }

3.3トラバーサル

 System.out.println("====遍历================================");
            //获取根节点
            Element root = document.getRootElement();

            // 遍历根节点下的子节点
            for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
                Element element = it.next();
                // do something
                System.out.println("根节下子节点名称:"+element.getName());
            }
            // 遍历子节点 author 下的子节点
            for (Iterator<Element> it = root.elementIterator("feed"); it.hasNext();) {
                Element foo = it.next();
                // do something
                System.out.println("author节点下节点名称:"+foo.getName());
            }
            // 后去根节点的属性
            for (Iterator<Attribute> it = root.attributeIterator(); it.hasNext();) {
                Attribute attribute = it.next();
                // do something
                System.out.println("根节下子节点属性:"+attribute.getName());
            }

XPathのGETを使用して3.4節

System.out.println("================================================");
            //使用 XPath 获取节点 获取多个节点
            List<Node> list = document.selectNodes("//feed/entry");
            for (Node node :list
                 ) {

                System.out.println("list node:"+node.getName());
            }
            Node node = document.selectSingleNode("//feed");

            System.out.println("node:"+node.getName());

ファイルへの保存3.5

//写到文件里面
            Document document1=Dom4jUtils.createDocument();
            FileWriter out = new FileWriter("foo.xml");
            document1.write(out);
            out.close();

3.6 XMLテキストファイルの転送

 Document xd=DocumentHelper.parseText(text);

3.7テキスト・ツー・XMLドキュメントオブジェクト

 String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);

XMLを使用して、3.8 XSLT変換

/**
     * 使用XSLT转换XML
     * */
    public static Document styleDocument(Document document, String stylesheet) throws Exception {

        TransformerFactory factory = TransformerFactory.newInstance();//实例化转换器工厂 TransformerFactory
        Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));// 创建一个转化格式对象

        DocumentSource source = new DocumentSource(document); // XML 源对象
        DocumentResult result = new DocumentResult(); //转换结果对象
        transformer.transform(source, result);//转换操作

        Document transformedDoc = result.getDocument();//获取转换后的文档
        return transformedDoc;
    }

コード例4 XStreamの

4.1エイリアス直接出力XMLを使用していません

Blog.java(路径のsrc /メイン/ javaの/ COM / fishpro / xmldom4j /ドメイン/ Blog.java)

public class Blog {
    private Author writer;
    private List entries = new ArrayList();

    public Blog(Author writer) {
        this.writer = writer;
    }

    public void add(Entry entry) {
        entries.add(entry);
    }

    public List getContent() {
        return entries;
    }
}

コードの一部

Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
        teamBlog.add(new Entry("first","My first blog entry."));
        teamBlog.add(new Entry("tutorial",
                "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));
        //1.如果不设置别名呢
        System.out.println(xstream.toXML(teamBlog));
        /** 1.不设置别名输出
         * <com.fishpro.xmldom4j.domain.Blog>
         *   <writer>
         *     <name>Guilherme Silveira</name>
         *   </writer>
         *   <entries>
         *     <com.fishpro.xmldom4j.domain.Entry>
         *       <title>first</title>
         *       <description>My first blog entry.</description>
         *     </com.fishpro.xmldom4j.domain.Entry>
         *     <com.fishpro.xmldom4j.domain.Entry>
         *       <title>tutorial</title>
         *       <description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description>
         *     </com.fishpro.xmldom4j.domain.Entry>
         *   </entries>
         * </com.fishpro.xmldom4j.domain.Blog>
         * */

4.2エイリアスダイレクト出力XML

コード上の定義ブログteamBlogの使用を注意してください。出力部の影響に注意してください

 //2.设置别名
        xstream.alias("blog", Blog.class);
        xstream.alias("entry", Entry.class);
        System.out.println(xstream.toXML(teamBlog));

        /** 2.设置别名
         * <blog>
         *   <writer>
         *     <name>Guilherme Silveira</name>
         *   </writer>
         *   <entries>
         *     <entry>
         *       <title>first</title>
         *       <description>My first blog entry.</description>
         *     </entry>
         *     <entry>
         *       <title>tutorial</title>
         *       <description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description>
         *     </entry>
         *   </entries>
         * </blog>
         * */

4.3ノードの名前に置き換えて

コード上の定義ブログteamBlogの使用を注意してください。出力部の影響に注意してください

 //3.writer 节点 转为 author节点
        System.out.println("2.writer 节点 转为 author节点");
        xstream.useAttributeFor(Blog.class, "writer");
        xstream.aliasField("author", Blog.class, "writer");
        System.out.println(xstream.toXML(teamBlog));

        xstream.addImplicitCollection(Blog.class, "entries");
        System.out.println(xstream.toXML(teamBlog));

        /** 3. author 替代了 write
         * <blog>
         *   <author>
         *     <name>Guilherme Silveira</name>
         *   </author>
         *   <entry>
         *     <title>first</title>
         *     <description>My first blog entry.</description>
         *   </entry>
         *   <entry>
         *     <title>tutorial</title>
         *     <description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description>
         *   </entry>
         * </blog>
         * */

4.4エンティティ・オブジェクトは、ノードの属性などの属性

コード上の定義ブログteamBlogの使用を注意してください。出力部の影響に注意してください

//4.writer 作为 blog 的属性
        System.out.println("4.作为blog的属性");
        xstream.useAttributeFor(Blog.class, "writer");
        xstream.registerConverter(new AuthorConverter());//作为blog的属性
        System.out.println(xstream.toXML(teamBlog));
        /** 4.writer 作为 blog 的属性
         * <blog author="Guilherme Silveira">
         *   <entry>
         *     <title>first</title>
         *     <description>My first blog entry.</description>
         *   </entry>
         *   <entry>
         *     <title>tutorial</title>
         *     <description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description>
         *   </entry>
         * </blog>
         * */

4.5を使用注釈@XStreamAlias

@XStreamAliasが同様に適用することができ、それはエンティティオブジェクトBeanのプロパティ名にも適用することができます

この例では、ユーザーや住所エンティティを使用して、彼らの関係は、ユーザーが複数のアドレスを持つことができています

ユーザー(路径のsrc /メイン/ javaの/ COM / fishpro / xmldom4j /ドメイン/ User.java)

@XStreamAlias("user")
public class User {
    @XStreamAlias("id")
    private Integer userId;

    @XStreamAlias("username")
    private String username;

    @XStreamImplicit
    private List<Address> addresses;

    public User(Integer userId,String username){
        this.userId=userId;
        this.username=username;
    }
    public User(Integer userId,String username,List<Address> addresses){
        this.userId=userId;
        this.username=username;
        this.addresses=addresses;
    }
    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}

住所(路径のsrc /メイン/ javaの/ COM / fishpro / xmldom4j /ドメイン/ Address.java)

@XStreamAlias("address")
public class Address {
    private String street;
    private String zipcode;
    private String mobile;

    public Address(String street,String zipcode,String mobile){
        this.street=street;
        this.zipcode=zipcode;
        this.mobile=mobile;
    }
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
System.out.println("5.使用注解");
        //5.使用注解
        xstream.processAnnotations(User.class);
        User msg = new User(1, "fishpro");
        System.out.println(xstream.toXML(msg));
        /** 使用注解 @XStreamAlias("user")
         * <user>
         *   <id>1</id>
         *   <username>fishpro</username>
         * </user>
         * */

4.6使用注釈@XStreamImplicit

コード上の定義ブログteamBlogの使用を注意してください。出力部の影響に注意してください

//6.使用注解 子节点是列表
        List<Address> addressList=new ArrayList<>();
        addressList.add(new Address("江苏省南京市玄武大道1000号","201001","1801989098"));
        addressList.add(new Address("江苏省南京市玄武大道1001号","201001","1811989098"));
        msg = new User(1, "fishpro",addressList);
        System.out.println(xstream.toXML(msg));
        /** 6.使用注解 子节点是列表
         * <user>
         *   <id>1</id>
         *   <username>fishpro</username>
         *   <address>
         *     <street>江苏省南京市玄武大道1000号</street>
         *     <zipcode>201001</zipcode>
         *     <mobile>1801989098</mobile>
         *   </address>
         *   <address>
         *     <street>江苏省南京市玄武大道1001号</street>
         *     <zipcode>201001</zipcode>
         *     <mobile>1811989098</mobile>
         *   </address>
         * </user>
         * */

4.9プロパティコンバータ

私たちは希望のフォーマットに変換する必要があるかもしれない日付に遭遇したとき、我々は増加したユーザーオブジェクトのプロパティを作成

    private Calendar created = new GregorianCalendar();

出力は、マルチノードを作成し、上記の例であり、以下の点に注意します

<user>
  <id>1</id>
  <username>fishpro</username>
  <address>
    <street>江苏省南京市玄武大道1000号</street>
    <zipcode>201001</zipcode>
    <mobile>1801989098</mobile>
  </address>
  <address>
    <street>江苏省南京市玄武大道1001号</street>
    <zipcode>201001</zipcode>
    <mobile>1811989098</mobile>
  </address>
  <created>
    <time>1565691626712</time>
    <timezone>Asia/Shanghai</timezone>
  </created>
</user>

次に、我々は新しいクラスコンバータの作成
(パスのsrc /メイン/ javaの/ COM / SingleValueCalendarConverterを fishpro / xmldom4j / utilに/ SingleValueCalendarConverter.java)

/**
 * 日期转换器
 * */
public class SingleValueCalendarConverter implements Converter {

    public void marshal(Object source, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
        Calendar calendar = (Calendar) source;
        writer.setValue(String.valueOf(calendar.getTime().getTime()));
    }

    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(new Date(Long.parseLong(reader.getValue())));
        return calendar;
    }

    public boolean canConvert(Class type) {
        return type.equals(GregorianCalendar.class);
    }
}

作成されたノードの主な動作例において、次のように変更

<user>
  <id>1</id>
  <username>fishpro</username>
  <address>
    <street>江苏省南京市玄武大道1000号</street>
    <zipcode>201001</zipcode>
    <mobile>1801989098</mobile>
  </address>
  <address>
    <street>江苏省南京市玄武大道1001号</street>
    <zipcode>201001</zipcode>
    <mobile>1811989098</mobile>
  </address>
  <created>1565691762404</created>
</user>

4.10のデシリアライズ

 XStream xstream = new XStream();
        xstream.alias("person", Person.class);//设置节点person的名称
        xstream.alias("phonenumber", PhoneNumber.class);
        Person joe = new Person("Joe", "Walnes");
        joe.setPhone(new PhoneNumber(123, "1234-456"));
        joe.setFax(new PhoneNumber(123, "9999-999"));
        String xml = xstream.toXML(joe);//对象转 xml
        System.out.println(xml);
        /** 输出简单示例xml
         * <person>
         *   <firstname>Joe</firstname>
         *   <lastname>Walnes</lastname>
         *   <phone>
         *     <code>123</code>
         *     <number>1234-456</number>
         *   </phone>
         *   <fax>
         *     <code>123</code>
         *     <number>9999-999</number>
         *   </fax>
         * </person>
         * */
        Person newJoe = (Person)xstream.fromXML(xml);//xml 转 对象

問題:

スレッドの例外 "メイン" java.lang.NoClassDefFoundErrorが:ORG /にJaxen / JaxenException

導入する必要があります

<!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>

参照

おすすめ

転載: www.cnblogs.com/fishpro/p/spring-boot-study-xml.html