summary
In our daily work, we often encounter the need to extract the information in xml files and convert it into entity classes. Combined with our own work experience, we make the following summary, which is convenient for people and ourselves.
Code example
xml format:
<?xml version="1.0" encoding="utf-8"?> <Device_Model> <Item device_id="2b5c0ac2-3708-4a85-ae20-34c75b281a6c" device_name="Low lockout indicator" bay_id="743803a4-0cd8-4f5c-a33b-992a2e31e837" bay_name="Switch cabinet" /> </Device_Model>
1. Add pom dependency:
<dependency> <groupId>xmlpull</groupId> <artifactId>xmlpull</artifactId> <version>1.1.3.1</version> </dependency>
When actually searching for information, we may know what package to refer to, but many bloggers do not give specific pom references, so we cannot determine which jar to refer to. Here is a small method:
You can search on the maven warehouse website: Maven Central Repository Search
Directly copy the contents in the red box to the pom file and refresh maven.
2. Define entity
package com.service.inspect.entity.task; import lombok.Data; @Data public class RobotPointEntity { /** * device_id */ private String deviceId; /** * device_name */ private String deviceName; /** * bay_id */ private String bayId; /** * bay_name */ private String bayName; }
The field of entity defined here can only correspond to the field in xml, because the actual set value needs to be manually mapped one by one. Therefore, even if we use the existing entity in the project and the field name cannot be modified, we can use the entity.
3. Reference a package
Because when I was looking for a solution, I referred to it Parsing xml documents via XmlPullParser - Zhang xuxiaoxia - blog Park y
But when the code in this article is copied, the system runs to
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
The following mistakes were reported when
Exception in thread "main" org.xmlpull.v1.XmlPullParserException: caused by: org.xmlpull.v1.XmlPullParserException: resource not found: /META-INF/services/org.xmlpull.v1.XmlPullParserFactory make sure that parser implementing XmlPull API is available
Find a solution to this problem by searching:
[xmlpull]XmlPull common errors - bystanders - blog Garden j
According to the method provided in this blog post, we need to http://kxml.sourceforge.net/ Download in kxml2.jar ,
Then import it into our project and use it
XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), Thread.currentThread().getContextClassLoader().getClass() );
Replace the above code.
Download the kxml2.jar package locally and import it into the project. Here, take intellij as an example to demonstrate the import operation:
Select kxml2.jar to download.
4.java
import com.service.inspect.entity.task.RobotPointEntity; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; public class Test { /** * According to the XML file path, it is parsed into entity * @param filePath xml route */ private void convert2Entity(String filePath) { List<RobotPointEntity> list = new ArrayList<>(); try { //Data definition RobotPointEntity robotPointEntity = null; //Get xmlpullparser object XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), Thread.currentThread().getContextClassLoader().getClass()); XmlPullParser parser = factory.newPullParser(); //Get input stream FileInputStream fis = new FileInputStream(filePath); //Set stream and character set parser.setInput(fis, "utf-8"); //Start parsing int event = parser.getEventType(); int num = 0; while (event != XmlPullParser.END_DOCUMENT) { switch (event) { //The start tag is usually used to initialize related sets or objects case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: String tagName = parser.getName(); //Get the attribute tag through getName if ("Item".equals(tagName)) { robotPointEntity = new RobotPointEntity(); //Get the marked attribute value through getAttributeName and getAttributeValue for (int i = 0; i < parser.getAttributeCount(); i++) { String name = parser.getAttributeName(i); String value = parser.getAttributeValue(i); switch (name) { case "device_id": robotPointEntity.setDeviceId(value); break; case "device_name": robotPointEntity.setDeviceName(value); case "bay_id": robotPointEntity.setBayId(value); break; case "bay_name": robotPointEntity.setBayName(value); break; default: break; } } list.add(robotPointEntity); } break; default: break; } event = parser.next(); } //After parsing, the collection is returned } catch (Exception e) { } } }
5. Call
Here I am the path of the xml file directly passed in, which can be directly referenced as follows
convert2Entity("robot.xml");
If the InputStream stream has been obtained, you can also change the input parameter to InputStream. Here, you can modify it yourself.
Reference:
java parsing xml documents - parsing through XmlPullParser - Zhang Xu Xiaoxia - blog Park