javaxmltostring
A. java String類型,轉化為XML形式的String類型。
importjava.lang.reflect.Field;
importjava.lang.reflect.Method;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
{
privateStringx="xxxx";
privateStringy="yyyy";
privateAa;
publicstaticvoidmain(String[]args){
BuildXmlFromPropertiest=newBuildXmlFromProperties();
Aa=newA("aXxxxx","aYyyyy");
Bb=newB("abXxxx","abYyyy");
a.setB(b);
t.setA(a);
Documentdoc=DocumentHelper.createDocument();
ElementbeginEle=doc.addElement("begin");
ElementstartEle=beginEle.addElement("start");
t.buildElement(t,"first",startEle);
System.out.println(doc.asXML());
}
publicvoidbuildElement(Objectobj,Stringtitle,ElementparentElement){
if(obj.getClass().getName().equals("java.lang.String")){
parentElement.addElement(title).setText(obj+"");
}else{
ElementsubElement=parentElement.addElement(title);
Field[]fields=obj.getClass().getDeclaredFields();
for(inti=0;i<fields.length;i++){
Methodmethod=null;
ObjectsubObj=null;
StringsubTitle=fields[i].getName();
try{
StringmethodName="get"+subTitle.substring(0,1).toUpperCase()+(subTitle.length()==1?"":subTitle.substring(1));
method=obj.getClass().getDeclaredMethod(methodName,null);
subObj=method.invoke(obj,null);
}catch(Exceptione){
e.printStackTrace();
}
buildElement(subObj,subTitle,subElement);
}
}
}
publicStringgetX(){
returnx;
}
publicStringgetY(){
returny;
}
publicAgetA(){
returna;
}
publicvoidsetX(Stringx){
this.x=x;
}
publicvoidsetY(Stringy){
this.y=y;
}
publicvoidsetA(Aa){
this.a=a;
}
}classA{
privateStringaX;
privateStringaY;
privateBb;
publicA(StringaX,StringaY){
this.aX=aX;
this.aY=aY;
}
publicStringgetAX(){
returnaX;
}
publicStringgetAY(){
returnaY;
}
publicvoidsetAX(StringaX){
this.aX=aX;
}
publicvoidsetAY(StringaY){
this.aY=aY;
}
publicBgetB(){
returnb;
}
publicvoidsetB(Bb){
this.b=b;
}
}
classB{
privateStringabX;
privateStringabY;
publicB(StringabX,StringabY){
this.abX=abX;
this.abY=abY;
}
publicStringgetAbX(){
returnabX;
}
publicStringgetAbY(){
returnabY;
}
publicvoidsetAbX(StringabX){
this.abX=abX;
}
publicvoidsetAbY(StringabY){
this.abY=abY;
}
}
主要就是用了遞歸,然後反射取欄位的名字和值
B. JAVA中,xml的string類型怎麼校驗是不是符合xml格式
使用jdk自帶的驗證api
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("instance.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
validator.validate(new DOMSource(document));
} catch (SAXException e) {
// instance document is invalid!
}
C. 用Java怎麼把String類型的字元串轉化為XML格式輸出
java中將string轉換成xml文件,使用開源jar包 dom4j:
packagecom.webdesk.swing.powertable.util;
importjava.io.ByteArrayInputStream;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importorg.dom4j.Document;
importorg.dom4j.DocumentException;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
publicclassXmlUtil{
(StringfileName){
try{
SAXReadersaxReader=newSAXReader();//新建一個解析類
DocumenttempDocument=saxReader.read(XmlUtil.class.getClassLoader().getResourceAsStream(fileName));//讀入一個文件
returntempDocument.asXML();
}catch(DocumentExceptione){
e.printStackTrace();
}
returnnull;
}
//將字元串string類型轉換成xml文件
publicstaticvoidstrChangeXML(Stringstr)throwsIOException{
SAXReadersaxReader=newSAXReader();
Documentdocument;
try{
document=saxReader.read(newByteArrayInputStream(str.getBytes("UTF-8")));
OutputFormatformat=OutputFormat.createPrettyPrint();
/**將document中的內容寫入文件中*/
XMLWriterwriter=newXMLWriter(newFileWriter(newFile("src/com/webdesk/swing/powertable/digester/cctv.xml")),format);
writer.write(document);
writer.close();
}catch(DocumentExceptione){
e.printStackTrace();
}
}
}
D. java 對象序列化到xml java 對象到xml 轉化為string
marshaller.marshal,明顯就有很多參數。用OutputStream那個就可以寫入String了。。
用XmlStreamWriter也是可以。
E. Java中用string拼接成xml
不建議對string拼接xml串容易出錯,java 有很多bean轉xml的工具,這樣容易很多,也不容易出錯,JAXB 是不錯的選擇,j2ee中自帶了,或者從搜索引擎中找 ,代碼參考,一個TRequest 類,他有幾個屬性 name,id等等
@XmlRootElement(name = "TRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class TRequest implements java.io.Serializable{
@XmlElement(name="name")
private String name;
@XmlElement(name="id")
private String id;
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
}
TRequest t= new TRequest();
t.setName("ddddddd");
t.setId("11");
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(t.getClass());
Marshaller marshaller = context.createMarshaller();
// marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
marshaller.marshal(t, writer);
String res=writer.toString();
writer.close();
F. java如何把String轉換成xml
導入dom4j這個包,然後使用這個包裡面的東西 進行解析與封裝
G. 請問java中怎麼將生成的XML轉化為字元串
我想問一下你的Document是什麼類型的?如果是org.dom4j.Document的話,你可以Document doc = ...;String str = doc.asXML();可以直接利用asXML()這個方法!其實的話就不清楚了!還得查下!
=========================
還是沒有查到!好像org.w3c.dom不提供這個方法!也可能是我沒弄對!在或者只能先存入文件,然後讀取...囧~~
不過樓主為什麼要用org.w3c.dom不用org.dom4j,一般說來現在比較公認dom4j是相對方便的!
H. java中已經獲得xml文件中的內容(是String 字元),如何解析
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
public class DuXMLDoc {
public List xmlElements(String xmlDoc) {
//創建一個新的字元串
StringReader read = new StringReader(xmlDoc);
//創建新的輸入源SAX 解析器將使用 InputSource 對象來確定如何讀取 XML 輸入
InputSource source = new InputSource(read);
//創建一個新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
try {
//通過輸入源構造一個Document
Document doc = sb.build(source);
//取的根元素
Element root = doc.getRootElement();
System.out.println("tasktypename:"+root.getAttributeValue("tasktypename"));
System.out.println("perfrenceNum:"+root.getAttributeValue("perfrenceNum"));
System.out.println(root.getName());//輸出根元素的名稱(測試)
//得到根元素所有子元素的集合
List jiedian = root.getChildren();
Element et = null;
for(int i=0;i<jiedian.size();i++){
et = (Element) jiedian.get(i);//循環依次得到子元素
if(et.getAttributeValue("inputindex").equals("1")){
et.setAttribute("name","1");
}
et.setAttribute("age","15");
System.out.println("name:"+et.getAttributeValue("name"));
System.out.println("value:"+et.getAttributeValue("value"));
System.out.println("inputindex:"+et.getAttributeValue("inputindex"));
System.out.println("perfrence:"+et.getAttributeValue("perfrence"));
System.out.println("age:"+et.getAttributeValue("age"));
}
// /**//*
// * 如要取<row>下的子元素的名稱
// */
// et = (Element) jiedian.get(0);
// List zjiedian = et.getChildren();
// for(int j=0;j<zjiedian.size();j++){
// Element xet = (Element) zjiedian.get(j);
// System.out.println(xet.getName());
// }
} catch (JDOMException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
DuXMLDoc doc = new DuXMLDoc();
String xml = "<?xml version=/"1.0/" encoding=/"UTF-8/"?>"+
"<submittask tasktypename=/"kind1/" perfrenceNum=/"2/">"+
"<input name=/"name/" value=/"123/" inputindex=/"1/" perfrence=/"2/"/>"+
"<input name=/"sex/" value=/"F/" inputindex=/"2/" perfrence=/"2/"/>"+
"</submittask>"
;
System.out.println(xml);
doc.xmlElements(xml);
}
}
I. java 將Object轉化為String類型的XML
只能拼接字元串。把要的xml不變的寫出來,然後把要變的用變數進行填補
J. java 中 String轉xml 解析問題
怎麼做我不知道。但是我覺得可以將真個xml內容轉成字元串。然後遍歷字元串。刪掉你不想要的字元就可以了額。。