com.thoughtworks.xstream.XStream.toXML()方法的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(10.4k)|赞(0)|评价(0)|浏览(229)

本文整理了Java中com.thoughtworks.xstream.XStream.toXML()方法的一些代码示例,展示了XStream.toXML()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。XStream.toXML()方法的具体详情如下:
包路径:com.thoughtworks.xstream.XStream
类名称:XStream
方法名:toXML

XStream.toXML介绍

[英]Serialize an object to a pretty-printed XML String.
[中]将对象序列化为打印精美的XML字符串。

代码示例

代码示例来源:origin: stackoverflow.com

public static boolean toXML(Object object, File file) {
  XStream xStream = new XStream();
  OutputStream outputStream = null;
  Writer writer = null;

  try {
    outputStream = new FileOutputStream(file);
    writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));
    xStream.toXML(object, writer);
  }
  catch (Exception exp) {
    log.error(null, exp);
    return false;
  }
  finally {
    close(writer);
    close(outputStream);
  }

  return true;
}

代码示例来源:origin: stackoverflow.com

map.put("island","faranga");
XStream magicApi = new XStream();
magicApi.registerConverter(new MapEntryConverter());
magicApi.alias("root", Map.class);
String xml = magicApi.toXML(map);
System.out.println("Result of tweaked XStream toXml()");
System.out.println(xml);
Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
assert extractedMap.get("name").equals("chris");
assert extractedMap.get("island").equals("faranga");

代码示例来源:origin: geoserver/geoserver

XStreamPersister persister = XSTREAM_PERSISTER_FACTORY.createXMLPersister();
XStream xs = persister.getXStream();
String xml = xs.toXML(source);
T copy = (T) xs.fromXML(xml);
return copy;

代码示例来源:origin: jenkinsci/jenkins

/**
 * Persists a list of installing plugins; this is used in the case Jenkins fails mid-installation and needs to be restarted
 * @param installingPlugins
 */
public static synchronized void persistInstallStatus(List<UpdateCenterJob> installingPlugins) {
  File installingPluginsFile = getInstallingPluginsFile();
if(installingPlugins == null || installingPlugins.isEmpty()) {
  installingPluginsFile.delete();
  return;
}
LOGGER.fine("Writing install state to: " + installingPluginsFile.getAbsolutePath());
Map<String,String> statuses = new HashMap<String,String>();
for(UpdateCenterJob j : installingPlugins) {
  if(j instanceof InstallationJob && j.getCorrelationId() != null) { // only include install jobs with a correlation id (directly selected)
    InstallationJob ij = (InstallationJob)j;
    InstallationStatus status = ij.status;
    String statusText = status.getType();
    if(status instanceof Installing) { // flag currently installing plugins as pending
      statusText = "Pending";
    }
    statuses.put(ij.plugin.name, statusText);
  }
}
  try {
  String installingPluginXml = new XStream().toXML(statuses);
    FileUtils.write(installingPluginsFile, installingPluginXml);
  } catch (IOException e) {
    LOGGER.log(SEVERE, "Failed to save " + installingPluginsFile.getAbsolutePath(), e);
  }
}

代码示例来源:origin: kiegroup/optaplanner

public static <T> T serializeAndDeserializeWithXStream(T input) {
  XStream xStream = new XStream();
  xStream.setMode(XStream.ID_REFERENCES);
  if (input != null) {
    xStream.processAnnotations(input.getClass());
  }
  XStream.setupDefaultSecurity(xStream);
  xStream.addPermission(new AnyTypePermission());
  String xmlString = xStream.toXML(input);
  return (T) xStream.fromXML(xmlString);
}

代码示例来源:origin: Netflix/eureka

@Test
public void testEncodingDecodingWithoutMetaData() throws Exception {
  Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications();
  XStream xstream = JsonXStream.getInstance();
  String jsonDocument = xstream.toXML(applications);
  Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument);
  assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true));
}

代码示例来源:origin: com.thoughtworks.xstream/xstream

/**
 * Serialize an object including the XStream to the given Writer as pretty-printed XML.
 * <p>
 * Warning: XStream will serialize itself into this XML stream. To read such an XML code, you
 * should use {@link XStreamer#fromXML(Reader)} or one of the other overloaded
 * methods. Since a lot of internals are written into the stream, you cannot expect to use such
 * an XML to work with another XStream version or with XStream running on different JDKs and/or
 * versions. We have currently no JDK 1.3 support, nor will the PureReflectionConverter work
 * with a JDK less than 1.5.
 * </p>
 * 
 * @throws IOException if an error occurs reading from the Writer.
 * @throws com.thoughtworks.xstream.XStreamException if the object cannot be serialized
 * @since 1.2
 */
public void toXML(final XStream xstream, final Object obj, final Writer out)
    throws IOException {
  final XStream outer = new XStream();
  XStream.setupDefaultSecurity(outer);
  final ObjectOutputStream oos = outer.createObjectOutputStream(out);
  try {
    oos.writeObject(xstream);
    oos.flush();
    xstream.toXML(obj, out);
  } finally {
    oos.close();
  }
}

代码示例来源:origin: kiegroup/optaplanner

protected <S extends Score, W extends TestScoreWrapper<S>> void assertSerializeAndDeserialize(S expectedScore, W input) {
  XStream xStream = new XStream();
  xStream.setMode(XStream.ID_REFERENCES);
  xStream.processAnnotations(input.getClass());
  XStream.setupDefaultSecurity(xStream);
  xStream.allowTypesByRegExp(new String[]{"org\\.optaplanner\\.\\w+\\.config\\..*",
      "org\\.optaplanner\\.persistence\\.xstream\\..*\\$Test\\w+ScoreWrapper"});
  String xmlString = xStream.toXML(input);
  W output = (W) xStream.fromXML(xmlString);
  assertEquals(expectedScore, output.getScore());
  String regex;
  if (expectedScore != null) {
    regex = "<([\\w\\-\\.]+)( id=\"\\d+\")?>" // Start of element
        + "\\s*<score( id=\"\\d+\")?>"
        + expectedScore.toString().replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]") // Score
        + "</score>"
        + "\\s*</\\1>"; // End of element
  } else {
    regex = "<([\\w\\-\\.]+)( id=\"\\d+\")?/>"; // Start and end of element
  }
  if (!xmlString.matches(regex)) {
    fail("Regular expression match failed.\nExpected regular expression: " + regex + "\nActual string: " + xmlString);
  }
}

代码示例来源:origin: Netflix/eureka

@Test
public void testEncodingDecodingWithMetaData() throws Exception {
  Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications();
  XStream xstream = JsonXStream.getInstance();
  String jsonDocument = xstream.toXML(applications);
  Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument);
  assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true));
}

代码示例来源:origin: org.codehaus.groovy/groovy

public static void serialize(final String name, final Object ast) {
  if (name == null || name.length() == 0) return;
  XStream xstream = new XStream(new StaxDriver());
  FileWriter astFileWriter = null;
  try {
    File astFile = astFile(name);
    if (astFile == null) {
      System.out.println("File-name for writing " + name + " AST could not be determined!");
      return;
    }
    astFileWriter = new FileWriter(astFile, false);
    xstream.toXML(ast, astFileWriter);
    System.out.println("Written AST to " + name + ".xml");
  } catch (Exception e) {
    System.out.println("Couldn't write to " + name + ".xml");
    e.printStackTrace();
  } finally {
    DefaultGroovyMethods.closeQuietly(astFileWriter);
  }
}

代码示例来源:origin: stackoverflow.com

import com.thoughtworks.xstream.XStream;

public class deepCopy {
  private static  XStream xstream = new XStream();

  //serialize with Xstream them deserialize ...
  public static Object deepCopy(Object obj){
    return xstream.fromXML(xstream.toXML(obj));
  }
}

代码示例来源:origin: Netflix/eureka

@Test
public void testEncodingDecodingWithoutMetaData() throws Exception {
  Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications();
  XStream xstream = XmlXStream.getInstance();
  String xmlDocument = xstream.toXML(applications);
  Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument);
  assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true));
}

代码示例来源:origin: stackoverflow.com

XStream xstream = new XStream();
 xstream.alias("person", Person.class);
 xstream.alias("persons", PersonList.class);
 xstream.addImplicitCollection(PersonList.class, "list");
 PersonList list = new PersonList();
 list.add(new Person("ABC",12,"address"));
 list.add(new Person("XYZ",20,"address2"));
 String xml = xstream.toXML(list);

代码示例来源:origin: stackoverflow.com

XStream xstream = new XStream();
  //converting object to XML
  String xml = xstream.toXML(myObject);
  //converting xml to object
  MyClass myObject = (MyClass)xstream.fromXML(xml);

代码示例来源:origin: Netflix/eureka

@Test
public void testEncodingDecodingWithMetaData() throws Exception {
  Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications();
  XStream xstream = XmlXStream.getInstance();
  String xmlDocument = xstream.toXML(applications);
  Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument);
  assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true));
}

代码示例来源:origin: apache/ignite

/**
 * Stores {@link IgniteConfiguration} to file as xml.
 *
 * @param cfg Ignite Configuration.
 * @param fileName A name of file where the configuration was stored.
 * @param resetMarshaller Reset marshaller configuration to default.
 * @param resetDiscovery Reset discovery configuration to default.
 * @throws IOException If failed.
 * @see #readCfgFromFileAndDeleteFile(String)
 */
public static void storeToFile(IgniteConfiguration cfg, String fileName,
  boolean resetMarshaller,
  boolean resetDiscovery) throws IOException, IgniteCheckedException {
  try(OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) {
    IgniteConfiguration cfg0 = new IgniteConfiguration(cfg);
    if (resetMarshaller)
      cfg0.setMarshaller(null);
    if (resetDiscovery)
      cfg0.setDiscoverySpi(null);
    cfg0.setWorkDirectory(U.defaultWorkDirectory());
    cfg0.setMBeanServer(null);
    cfg0.setGridLogger(null);
    new XStream().toXML(cfg0, out);
  }
}

代码示例来源:origin: stackoverflow.com

XStream xstream = new XStream();
// marshalling
String xml = xstream.toXML(domainObject);
// unmarshalling
domainObject = xstream.fromXML(xml);

代码示例来源:origin: jenkinsci/jenkins

String xml = Jenkins.XSTREAM.toXML(src);
Node result = (Node) Jenkins.XSTREAM.fromXML(xml);
result.setNodeName(name);
if(result instanceof Slave){ //change userId too

代码示例来源:origin: stackoverflow.com

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");

XStream xStream = new XStream();
xStream.alias("Strings", List.class);
xStream.alias("String", String.class);
String result = xStream.toXML(list);

代码示例来源:origin: org.sonatype.sisu.assembler/sisu-assembler

private static Object adapt( final Object toConvert, final String fromPackage, final String toPackage )
{
  final XStream xstream = new XStream();
  final String xml = xstream.toXML( toConvert ).replace( fromPackage, toPackage );
  final Object converted = xstream.fromXML( xml );
  return converted;
}

相关文章