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内容转成字符串。然后遍历字符串。删掉你不想要的字符就可以了额。。