The use of XMLParser, an XML parsing tool based on Dom4J

Introduction to XMLParser

XMLParser is an Android XML file parsing and generating tool that uses annotations to generate and parse tags in XML files.
Import using gradle

implementation "lee.hua.xmlparse:xmlparse:2.4.3"

Simple to use

Scenario: A description of book information. A book contains information such as book title, number of pages, price, author, publisher, etc. We use JAVA objects to simply express it, as follows

@XmlBean(name = "BookNode")//XMLParser类注解,表示此类是一个XML标签,name表示输出的标签名
public class Book {
    
    
    @XmlAttribute 
    private String name;//书名
    @XmlAttribute
    private Integer page;//页数
    @XmlAttribute
    private Float price;//价格
    @XmlSingleNode(name = "Publisher",nodeType = Publisher.class)//XMLParser属性注解,表示一个子标签
    private Publisher publishier;//出版商
    @XmlListNode(name = "Author",nodeType = Author.class)//XMLParser属性注解,表示多个子标签
    private List<Author> authors;//作者,多个
	//省略无参构造 getter setter 和 toString 方法
}
@XmlBean(name = "Author")
public class Author {
    
    
    @XmlAttribute
    private String name;//作者名
    //省略无参构造 getter setter 和 toString 方法
}
@XmlBean(name = "Publisher")
public class Publisher {
    
    
    @XmlAttribute(name = "PUB") //XMLParser属性注解,name表示输出的属性名
    private String pub;//出版社名称
    //省略无参构造 getter setter 和 toString 方法
}

After defining the object, we can use XMLParser to output and parse. The
generated XML code is as follows:

//生成XML文件
public void generate(){
    
    
	//生成book数据
    Book book = new Book();
    book.setName("XMLParser解析");
    book.setPage(55);
    book.setPrice(37.5f);
    book.setPublishier(new Publisher("中国花花出版社"));
    List<Author> authors = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
    
    
       Author author = new Author("author0"+i);
       authors.add(author);
    }
    book.setAuthors(authors);
	//设置注解扫描路径
    XMLAPI.setXmlBeanScanPackage("com.lee");
    //输出book对象
    XMLAPI.writeObj2Xml(book,"/Users/lijie/Desktop/test.xml");
}

result:

text.xml
<?xml version="1.0" encoding="UTF-8"?>
<BookNode name="XMLParser解析" page="55" price="37.5">
    <Publisher PUB="中国花花出版社"/>
    <Author name="author00"/>
    <Author name="author01"/>
    <Author name="author02"/>
    <Author name="author03"/>
</BookNode>

To parse the XML file, we use the test.xml file just output as the parsing object. The code is as follows:

public void readXML(){
    
    
	//设置注解扫描路径
	XMLAPI.setXmlBeanScanPackage("com.lee");
	//调用readXML读取文件,并强转为Book对象
    Book book = (Book) XMLAPI.readXML(new FileInputStream("/Users/lijie/Desktop/test.xml"));
    //打印
    System.out.println(book);
}

Print result:

Book{
	name='XMLParser解析', page=55, price=37.5, 
	publishier=Publisher{pub='中国花花出版社'},
	Author{name='author00'},
	Author{name='author01'}, 
	Author{name='author02'}, 
	Author{name='author03'}]
}

Detailed use of XMLParser

First introduce the annotation tags used during use

Label name Annotation object effect Attributes
@XmlBean JAVA class Represents an XML tag name: the name of the XML tag to be operated
@XmlAttribute Basic data types and String attributes of JAVA class members Represents the attributes of an XML tag name: the attribute name of the label to be operated
@XmlListNode JAVA class collection member properties Represents a collection of multiple identical subtags name: the name of the subtag to be operated on. nodetype: the JAVA class corresponding to the subtag
@XmlSingleNode JAVA class member object properties Represents a single subtag name: the name of the subtag to be operated on. nodetype: the JAVA class corresponding to the subtag
@Ignore JAVA class member attributes Indicates to ignore this attribute and not to parse and generate no

Modeling

After introducing the annotation tags above, let’s start the actual combat:
first create an XML file whose root node is User

<User name="test" age="18" marry="true" married="true">
	<Books>
		<Book name="java"/>
		<Book name="android"/>
	</Books>
	<Phone number="110110110" type="home"/>
	<Phone number="221221221" type="company"/>
</User> 

According to the XML structure, we can construct the corresponding JAVA object relationship

/**
 * 根据XML文件解析得来最外层User标签
 */
@XmlBean//标记为XML标签
public class User {
    
    
    @XmlAttribute//标记为标签属性
    private String name;
    @XmlAttribute//标记为标签属性
    private int age;
    @XmlAttribute//标记为标签属性
    private boolean marry;
    @Ignore//忽略的标签属性
    private boolean married = false;
    @XmlSingleNode(name = "Books", nodeType = Books.class)//单个子节点 name=节点名字,nodeType=节点对应的JAVA类对象
    private Books books;
    @XmlListNode(name = "Phone", nodeType = Phone.class)//多个子节点
    private List<Phone> phones;

	//getter 和 setter
}
@XmlBean
public class Books {
    
    
    @XmlListNode(name = "Book",nodeType = Book.class)
    private List<Book> books;
    //getter 和 setter
}
@XmlBean
public class Book {
    
    
    @XmlAttribute
    private String name;
    //getter 和 setter
}
@XmlBean
public class Phone {
    
    
    @XmlAttribute(name = "number")//解析属性为number的标签属性
    private String phoneNum;
    @XmlAttribute
    private String type;
    //getter 和 setter
}

Read XML file

After the model is built, XMLParser has a XMLAPIclass that provides all operations generated by XML parsing. Very simple, look at the code directly:

@Test
public void testXML(){
    
    
  //设置标签类(之前定义的User、Books等)的包路径
  XMLAPI.changPackageName("lee.hua.databinding.xml_parse");
  //调用对应的 ClassLoader,某些特殊情况下不设置会找不到对应的class
  XMLAPI.setClassLoader(context.getClassLoader());
  //调用XMLAPI.readXML()读取指定路径的XML文件
  User userBean = (User) XMLAPI.readXML("/Users/lijie/Desktop/f.xml");
  //打印user对象信息
  System.out.println("XMLParser====="+ userBean);
}

Output:

XMLParser=====UserBean{name='test', age=18, marry=true, married=false, 
books=Books{books=[Book{name='java'}, Book{name='android'}]}, 
phones=[Phone{phoneNum='110110110', type='home'}, 
Phone{phoneNum='221221221', type='company'}]}

analysis:

We can find that the parsing effect of Ignore and XmlAttribute has come out, the user attribute married ignores parsing, and the phoneNum attribute of Phone is also successfully assigned

Generate XML file

The generation of XML is relatively simple, and it only needs to be called XMLAPI.writeObj2Xml(Object object,String ouputPath). Of course, the premise is: define the XmlBean object in advance.
Above code:

 @Test
 public void testXML(){
    
    
	 //读取f.xml文件,文件内容就是上面定义的User
     XMLAPI.changPackageName("lee.hua.databinding.xml_parse");
     File file = new File("/Users/lijie/Desktop/f.xml");
     User userBean = (User) XMLAPI.readXML(new FileInputStream(file));
     System.out.println("XMLParser====="+ userBean);
	 //为解析出的对象新加一本书,名称为XMLParser,输出到f2.xml
     userBean.books.getBooks().add(new Book("XMLParser"));
     XMLAPI.writeObj2Xml(userBean,"/Users/lijie/Desktop/f2.xml");
 }

result:

<?xml version="1.0" encoding="UTF-8"?>

<User name="test" age="18" marry="true">
    <Books>
        <Book name="java"/>
        <Book name="android"/>
        <Book name="XMLParser"/>
    </Books>
    <Phone number="110110110" type="home"/>
    <Phone number="221221221" type="company"/>
</User>

analysis:

According to the content of the XML file, it can be found that the married marked by Ignore is not output, and the phoneNum in Phone is also output according to name="number".

to sum up

The above is the basic usage of XMLParser. I have worked for two years and have limited ability. I have been using Youdaoyun to take notes before. I just started to write blog posts. There are many shortcomings in the article and there are still many optimizations and modifications in the program. I hope you can support it. Finally, attach the GitHub address lijieqing/XMLParser

Guess you like

Origin blog.csdn.net/lijie2664989/article/details/79422296