WebService (iv) Operations on XML (Jaxbcontext-based XML and object conversions) __web

Source: Internet
Author: User
Tags bind xpath
<span>jaxbcontext to complete XML and object conversion operations
</span> package
org.xml;

public class Classroom {

	private int id;
	private String name;
	private int grade;
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetName () {
		return name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	public int Getgrade () {
		return grade;
	}
	public void Setgrade (int grade) {
		this.grade = grade;
	}
	Public Classroom () {
		super ();
	}
	Public classroom (int ID, String name, int grade) {
		super ();
		This.id = ID;
		this.name = name;
		This.grade = grade;
	}
}

Package org.xml;

Import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement public
class Student {

	private int id;
	private String name;
	private int age;
	Private classroom classroom;
	
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetName () {
		return name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	public int getage () {
		return age;
	}
	public void Setage (int.) {
		this.age = age;
	}
	Public Classroom Getclassroom () {
		return classroom;
	}
	public void Setclassroom (classroom classroom) {
		this.classroom = classroom;
	}
	public Student (int ID, String name, Int. age, Classroom classroom) {
		super ();
		This.id = ID;
		this.name = name;
		This.age = age;
		This.classroom = classroom;
	}
	Public Student () {
		super ();
		TODO auto-generated constructor stub
	}
}

Package org.xml;

Import Java.io.StringReader;
Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Marshaller;

Import Javax.xml.bind.Unmarshaller;

Import Org.junit.Test; 
			public class Testjaxb {@Test public void test01 () {try {Jaxbcontext ctx = jaxbcontext.newinstance (Student.class);
			Orchestration: Converting an object to XML Marshaller Marshaller = Ctx.createmarshaller ();
			Student stu = new Student (1, "Zhangsan", +, new classroom (1, "Computer", 2010));
		Marshaller.marshal (Stu, System.out);
		} catch (Jaxbexception e) {e.printstacktrace ();
			}} @Test public void test02 () {try {Jaxbcontext ctx = jaxbcontext.newinstance (Student.class); String xml = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "standalone=\" yes\ "? ><student><age>21</ age><classroom><grade>2010</grade><id>1</id><name> Computer </name></ Classroom><id>1</id><name>zhangsan</name></student> ";
			Orchestration: Converting an object to XML Unmarshaller Unmarshaller = Ctx.createunmarshaller ();
			Student stu = (Student) Unmarshaller.unmarshal (new StringReader (XML));
		System.out.println (Stu.getname () +stu.getclassroom (). GetName ());
		} catch (Jaxbexception e) {e.printstacktrace ();
 }
	}
}


Stax-based read and change operations on XML files

<?xml version= "1.0" encoding= "UTF-8"?> <bookstore> <book category= "COOKING" > <title lang= "en" ; Everyday italian</title> <author>giada De laurentiis</author> <year>2005</year> &LT;PR ice>30.00</price> </book> <book category= "Children" > <title lang= "en" >harry potter</ Title> <author>j K. rowling</author> <year>2005</year> <price>29.99</price> & lt;/book> <book category= "WEB" > <title lang= "en" >xquery Kick start</title> <author>james M cgovern</author> <author>per bothner</author> <author>kurt Cagle</author> <author& Gt James linn</author> <author>vaidyanathan nagarajan</author> <year>2003</year> <pri ce>49.99</price> </book> <book category= "WEB" > <title lang= "en" >learning xml</title > <author>erik T. ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> 

Package org.xml.stax;
Import java.io.IOException;

Import Java.io.InputStream;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.stream.EventFilter;
Import Javax.xml.stream.FactoryConfigurationError;
Import Javax.xml.stream.XMLEventReader;
Import Javax.xml.stream.XMLInputFactory;
Import Javax.xml.stream.XMLOutputFactory;
Import javax.xml.stream.XMLStreamConstants;
Import javax.xml.stream.XMLStreamException;
Import Javax.xml.stream.XMLStreamReader;
Import Javax.xml.stream.XMLStreamWriter;
Import javax.xml.stream.events.XMLEvent;
Import Javax.xml.transform.OutputKeys;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Transformer;
Import javax.xml.transform.TransformerConfigurationException;
Import javax.xml.transform.TransformerException;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.TransformerFactoryConfigurationError; Import JAVAX.XML.transform.dom.domsource;
Import Javax.xml.transform.stream.StreamResult;
Import Javax.xml.xpath.XPath;
Import javax.xml.xpath.XPathConstants;
Import javax.xml.xpath.XPathExpressionException;

Import Javax.xml.xpath.XPathFactory;
Import Org.junit.Test;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import org.w3c.dom.NodeList;

Import org.xml.sax.SAXException; /** * Cursor-based * are provided by the Java API * * * public class Teststax {/** * output node type representation number * Based on cursor */@Test public void Test
		() {Xmlinputfactory factory = Xmlinputfactory.newinstance ();
		InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml");
			Xmlstreamreader reader = Factory.createxmlstreamreader (IS);
				while (Reader.hasnext ()) {int type = Reader.next ();
				if (type = = Xmlstreamconstants.start_element) {System.out.println (Reader.getname ());
				}else if (type = = Xmlstreamconstants.characters) {System.out.println (Reader.gettext (). Trim ()); }else if (type = = XmlsTreamconstants.end_element) {System.out.println (Reader.getname ());
		}}} catch (Factoryconfigurationerror e) {e.printstacktrace ();
		} catch (Xmlstreamexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Output the type of book that exists * * based on CURSOR */@Test public void test02 () {Xmlinputfactory factory = Xmlinputfact
		Ory.newinstance ();
		InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml");
			Xmlstreamreader reader = Factory.createxmlstreamreader (IS);
				while (Reader.hasnext ()) {int type = Reader.next ();
					if (type = = xmlstreamconstants.start_element) {String name = Reader.getname (). toString ();
					if (Name.equals ("book")) {System.out.println (reader.getattributename (0) + ":" +reader.getattributevalue (0));
		}}}} catch (Factoryconfigurationerror e) {e.printstacktrace (); } catch (XmlstrEamexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Output the type of book that exists * * based on CURSOR */@Test public void test03 () {Xmlinputfactory factory = Xmlinputfact
		Ory.newinstance ();
		InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml");
			Xmlstreamreader reader = Factory.createxmlstreamreader (IS);
				while (Reader.hasnext ()) {int type = Reader.next (); Determines whether the node type is a start or end or a text node, then processes according to the situation//cursor-based method if (type = = xmlstreamconstants.start_element) {String name = RE
					Ader.getname (). toString ();
						if (Name.equals ("title")) {System.out.println (reader.getattributename (0) + ":" +reader.getattributevalue (0));
					System.out.print (Reader.getelementtext () + ":");
					} if (Name.equals ("price")) {System.out.println (Reader.getelementtext () + ":"); }}}} catch (Factoryconfigurationerror e) {E.PRintstacktrace ();
		} catch (Xmlstreamexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Output the type of book that exists * * Based on the way of iteration */@Test public void test04 () {Xmlinputfactory factory = Xmlinputfact
		Ory.newinstance ();
		InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml");
			Iterative model-based operation Xmleventreader reader = Factory.createxmleventreader (IS);
			int num = 0;
				while (Reader.hasnext ()) {//xmlevent to get whether it is a certain node xmlevent event = Reader.nextevent ();
					if (Event.isstartelement ()) {//Event.asxxxxx to convert node String name = Event.asstartelement (). GetName (). toString ();
					if (Name.equals ("title")) {System.out.print (Reader.getelementtext () + ":");
					} if (Name.equals ("price")) {System.out.println (Reader.getelementtext () + ":");
			}} num++;
		} System.out.println ("Traversal count:" +num); } catch(Factoryconfigurationerror e)
		{E.printstacktrace ();
		} catch (Xmlstreamexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Output existing Book type * filter * efficiency above direct above method */@Test public void test05 () {Xmlinputfactory factory = X
		Mlinputfactory.newinstance ();
		InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml"); Filter-based filtering allows efficient filtering of nodes that do not operate, and is highly efficient xmleventreader reader = Factory.createfilteredreader ( Factory.createxmleventreader (IS), new EventFilter () {@Override public boolean accept (Xmleve NT Event) {//Returns TRUE to indicate that a return of false indicates that the IF (Event.isstartelement ()) {String name = even is not displayed)
												T.asstartelement (). GetName (). toString (); if ("title". Equals (name) | | "
												Price ". Equals (name)) {return true;
			}} return false;							}
									});
			int num = 0;
				while (Reader.hasnext ()) {//xmlevent to get whether it is a certain node xmlevent event = Reader.nextevent ();
					if (Event.isstartelement ()) {//Event.asxxxxx to convert node String name = Event.asstartelement (). GetName (). toString ();
					if (Name.equals ("title")) {System.out.print (Reader.getelementtext () + ":");
					} if (Name.equals ("price")) {System.out.println (Reader.getelementtext () + ":");
			}} num++;
		} System.out.println ("Traversal count:" +num);
		} catch (Factoryconfigurationerror e) {e.printstacktrace ();
		} catch (Xmlstreamexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Output the type of book that exists * Documentbuilderfactory * can read part of the document * efficiency is higher than direct read all */@Test public void test06 (
		) {InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml"); Creating a Document Object Documentbuilder DB= Documentbuilderfactory.newinstance (). Newdocumentbuilder ();
			Document processing object created by Documentbuilder documents doc = Db.parse (IS);
			Create XPath XPath XPath = xpathfactory.newinstance (). Newxpath (); The first parameter is XPath, the second parameter is the document NodeList list = (NodeList) xpath.evaluate ("//book[@category = ' WEB ']", Doc,
			Xpathconstants.nodeset);
			The result of traversing output int length = List.getlength ();
				for (int i=0;i<length;i++) {element e = (element) list.item (i);
			System.out.println (E.getelementsbytagname ("title"). Item (0). Gettextcontent ());
		}} catch (Parserconfigurationexception e) {e.printstacktrace ();
		} catch (Saxexception e) {e.printstacktrace ();
		} catch (IOException e) {e.printstacktrace ();
		} catch (Xpathexpressionexception e) {e.printstacktrace ();
				}finally{if (is!=null) {try {is.close ();
				} catch (IOException e) {e.printstacktrace (); }}}}/** * Create XML */@Test public void test07 () {try {xmlstreamwriter XSW = XMLOUTPUtfactory.newinstance (). Createxmlstreamwriter (System.out);
			Version number Xsw.writestartdocument ("UTF-8", "1.0");
			Xsw.writeenddocument ();
			String ns = "HTTP://AA:DD";
			Xsw.writestartelement ("Test", "person", NS);
			Xsw.writestartelement (NS, "id");
			Xsw.writecharacters ("1");
			Xsw.writeendelement ();
			Xsw.writeendelement ();
			Xsw.flush ();
		Xsw.close ();
		} catch (Xmlstreamexception e) {e.printstacktrace ();
		} catch (Factoryconfigurationerror e) {e.printstacktrace ();
		}}/** * Use Transform to modify node */@Test public void test08 () {InputStream is = null;
			try {is = TestStax.class.getResourceAsStream ("books.xml");
			Create Document Object Documentbuilder db = Documentbuilderfactory.newinstance (). Newdocumentbuilder ();
			Document processing object created by Documentbuilder documents doc = Db.parse (IS);
			Create XPath XPath XPath = xpathfactory.newinstance (). Newxpath ();
			Transformer tran = Transformerfactory.newinstance (). Newtransformer (); Set output Properties Tran.setoutputproperty (OUTPUtkeys.encoding, "UTF-8");
			Tran.setoutputproperty (outputkeys.indent, "yes"); The first parameter is XPath, the second parameter is the document NodeList list = (NodeList) xpath.evaluate ("//book[title= ' Harry Potter ']", Doc,
			Xpathconstants.nodeset);
			Gets the price node Element book = (element) list.item (0);
			Element price = (Element) (Book.getelementsbytagname ("price"). Item (0));
			Price.settextcontent ("55555");
			Result result = new Streamresult (System.out);
		Modify Code Tran.transform (new Domsource (DOC), result) through transform;
		} catch (Parserconfigurationexception e) {e.printstacktrace ();
		} catch (Saxexception e) {e.printstacktrace ();
		} catch (IOException e) {e.printstacktrace ();
		} catch (Xpathexpressionexception e) {e.printstacktrace ();
		} catch (Transformerconfigurationexception e) {e.printstacktrace ();
		} catch (Transformerfactoryconfigurationerror e) {e.printstacktrace ();
		} catch (Transformerexception e) {e.printstacktrace (); }finally{if (is!=null) {try {Is.closE ();
				} catch (IOException e) {e.printstacktrace ();
 }
			}
		}
	}

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.