Rectangle 27 2

I have seen that tutorial but it didn't help.

java - Format XML generated by Xstream - Stack Overflow

java xml xstream
Rectangle 27 4

XStream xstream = new XStream();
xstream.registerConverter(new JavaBeanConverter(xstream.getClassMapper(), "class"), -20);

java - XStream to use getter for serialization - Stack Overflow

java xml spring xstream
Rectangle 27 4

PrettyPrintWriter
XStream xstream = //...whatever
// p is my object needing xml serialization
xstream.toXML(p)
BufferedOutputStream stdout = new BufferedOutputStream(System.out);
xstream.marshal(p, new PrettyPrintWriter(new OutputStreamWriter(stdout)));
new PrettyPrintWriter(writer, new char[]{' ', ' ', ' ', ' '})

@aetheria: Thanks, I came across exactly that solution myself.

This does not work if you are using the Stax driver. Any other ideas?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Format XML generated by Xstream - Stack Overflow

java xml xstream
Rectangle 27 6

Will marshaling write all contents of the file, though I'm just updating a single element?

Yes. The marshaller doesn't know or care how much you changed, all it cares about is the state of the objects at the time of marshalling.

is there a better way to marshal and update a specific element of an XML file using JAXB or XStream?

Not really. If you need to update fragments of the data, then the data really should be stored as separate files, rather than as one big file.

How do I make a marshalling operation thread safe, in case multiple threads might marshal to the same XML file?

Using regular java thread synchronization techniques (i.e. using synchronized methods, or using the locking facilities in java.util.concurrent).

java - How to Marshall using JAXB (or XStream) to update an XML file w...

java xml-serialization jaxb xstream
Rectangle 27 2

The solution is not straighforward.

The marshal (Object to XML) is quite simple, the problem comes when you have to unmarshal (XML to Object) it.

What happens is that when XStream starts reading the XML and it finds a Product tag, it can't know for sure if it is a "Product" or "OtherProduct" object, since the tag name is the same.

So, you have to teach XStream to look ahead and check for something that you know that makes them different. In that case, the inner attributes "Name" and "Id".

You can teach XSTream how to do that writing Converters.

The solution above shows how to solve the problem.

@XStreamAlias("Product")
public class Product {

    @XStreamAlias("Name")
    private String name;

    public Product() {
    }

    public Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;

    }

}
@XStreamAlias("Product")
public class OtherProduct {

    @XStreamAlias("Id")
    private int id;

    public OtherProduct() {

    }

    public OtherProduct(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}
@XStreamAlias("Groups")
public class GroupData {
    @XStreamAlias("Products")
    private List<Product> products = new ArrayList<>();

    @XStreamAlias("OtherProducts")
    private List<OtherProduct> otherProducts = new ArrayList<>();

    public void add(Product product) {
        getProducts().add(product);
    }

    public void add(OtherProduct otherProduct) {
        getOtherProducts().add(otherProduct);
    }

    public List<Product> getProducts() {
        return products;
    }

    public List<OtherProduct> getOtherProducts() {
        return otherProducts;
    }

}
public class ProductConverter implements Converter {
    private ProductUnmarshaller productUnmarshaller = new ProductUnmarshaller();

    @Override
    public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) {
        return clazz.equals(Product.class);
    }

    @Override
    public void marshal(Object object, HierarchicalStreamWriter hsw, MarshallingContext mc) {
        Product product = (Product) object;
        hsw.startNode("Name");
        hsw.setValue(product.getName());
        hsw.endNode();
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc) {
        return productUnmarshaller.unmarshal(hsr, uc);
    }

}
public class OtherProductConverter implements Converter {
    private ProductUnmarshaller productUnmarshaller = new ProductUnmarshaller();

    @Override
    public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) {
        return clazz.equals(OtherProduct.class);
    }

    @Override
    public void marshal(Object object, HierarchicalStreamWriter hsw, MarshallingContext mc) {
        OtherProduct otherProduct = (OtherProduct) object;
        hsw.startNode("Id");
        hsw.setValue(Integer.toString(otherProduct.getId()));
        hsw.endNode();
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc) {
        return productUnmarshaller.unmarshal(hsr, uc);
    }


}
public class ProductUnmarshaller {

    public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc) {
        hsr.moveDown();

        String nodeName = hsr.getNodeName();
        String nodeValue = hsr.getValue();

        hsr.moveUp();

        if ("Name".equals(nodeName)) {
            return new Product(nodeValue);
        } else if ("Id".equals(nodeName)) {
            return new OtherProduct(Integer.parseInt(nodeValue));
        } else {
            return null;
        }



    }

}

And finally, a class using it all:

public class ProductTest {
    @Test
    public void test() {
        Product productOne = new Product("One");
        Product productTwo = new Product("Two");

        OtherProduct otherProduct1 = new OtherProduct(1);
        OtherProduct otherProduct2 = new OtherProduct(2);

        GroupData group = new GroupData();
        group.add(productOne);
        group.add(productTwo);
        group.add(otherProduct1);
        group.add(otherProduct2);

        XStream xs = new XStream();
        xs.processAnnotations(GroupData.class);
        xs.processAnnotations(OtherProduct.class);
        xs.processAnnotations(Product.class);
        xs.registerConverter(new ProductConverter());
        xs.registerConverter(new OtherProductConverter());
        String xml = xs.toXML(group);
        System.out.println(xml);
        GroupData gd = (GroupData) xs.fromXML(xml);

        for (Product product: gd.getProducts()) {
            System.out.println(product.getName());
        }

        for (OtherProduct otherProduct: gd.getOtherProducts()) {
            System.out.println(otherProduct.getId());
        }

    }

}

java - xStream parsing XML with duplicate tags - Stack Overflow

java xml xstream
Rectangle 27 2

XStream xstream = new XStream();
    Data<ContentX> data = new Data<ContentX>();
    data.action="push";
    data.params=new ContentX();
    data.params.name="where";
    data.params.tel="1712";

    xstream.alias("data", Data.class);
    xstream.alias("params", ContentX.class);
    String xml = xstream.toXML(data);
    System.out.println(xml);

    Data<ContentX> result = (Data<ContentX>)xstream.fromXML(xml);
    System.out.println(result.action);
    System.out.println(result.params.name);
    System.out.println(result.params.tel);

java - Deserializing a XML to Object with xstream when an attribute is...

java xml generics xstream
Rectangle 27 1

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

I do not believe this use case can be handled by XStream. If you are open to using other technologies, below is an example of how it could be done with MOXy. Using the @XmlPath extension.

@XmlPath("AnotherData/Records/AnotherRecord")
List<AnotherRecord> list;

Below is what the fully mapped Root class would look like. JAXB does not require any annotations (see: http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html), but since the XML elements in your document do not match the default naming rules some annotations are required.

To specify MOXy as your JAXB provider you need to add a file called jaxb.properties in the same package as your domain classes with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

You can use the following demo code to prove that everything works:

package forum11970410;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11970410/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Version>2.0</Version>
   <Name>John</Name>
   <Age>18</Age>
   <UserId>22491</UserId>
   <Country>USA</Country>
   <AnotherData>
      <Records>
         <AnotherRecord>
            <Field1>XXX</Field1>
            <Field2>XX</Field2>
            <Field3>CCCCCCCC</Field3>
            <Field4>XXX9000</Field4>
            <Field5>XXX00345</Field5>
         </AnotherRecord>
      </Records>
   </AnotherData>
</Root>

java - Define XML Structure with Xstream - Stack Overflow

java xml structure xstream
Rectangle 27 1

If you make the fields public, Jackson can use them instead of getter/setter methods. There is also an annotation @JsonProperty to cause that.

public class KeyValuePair {

    @JsonProperty
    private int value;
    @JsonProperty
    private String key;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)

Thanks, would you be able to tell me which annotation? I been searching for it and couldn't find anything.

I was looking for the XStream XML annotation. Sorry if the question wasn't clear.

java - XStream to use getter for serialization - Stack Overflow

java xml spring xstream
Rectangle 27 1

ClassNotFoundException: The class its looking for is not available in your classPath

for your stack trace it says org.codehaus.jettison.mapped.Configuration no found. you are missing lib jettison, If you are using maven you can add

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.3.5</version>
</dependency>

i am using eclipse and when i go to the java build path the jettison-1.3.3.jar is under the Web App Libraries. Its in the WEB-INF/lib folder. does this not do that?

java - Using JSON and Xstream - Stack Overflow

java json web-services xstream
Rectangle 27 4

There are a number of different ways to do this. You might want to check out XStream or JAXB. There are tutorials and the examples.

How to retrieve element value of XML using Java? - Stack Overflow

java xml
Rectangle 27 4

nltk.corpus.reuters.words() returns a list that contains some "words" that can not be valid XML element names, for example, .'".

When dicttoxml() encounters such a key in the afd dictionary it generates an element with the name "key" and with an attribute name containing the original (invalid) name, e.g.

<key type="int" name=".'"">1</key>

Clearly this is invalid XML and all XML parsers should (rightly) complain about it. xmllint does and you've found that XStream does too. dicttoxml() is not replacing characters such as double quotes (") with . To work around this you can call xml_escape() on the keys before running dicttoxml() (see dict comprehension below):

from __future__ import unicode_literals

import nltk.corpus
from nltk import FreqDist
from dicttoxml import dicttoxml, xml_escape

#corpus
words = [w.decode('utf-8', errors='replace') for w in nltk.corpus.reuters.words()]
fd = FreqDist(words)
afd = {xml_escape(k):v for k,v in fd.items()}

# special key for sum
afd['__sum__']=fd.N()

xml = dicttoxml(afd)

f=open('frequencies.xml', 'w')
f.write(xml)
f.close()

You are a beautiful human being.

Does it please you to believe that I am a beautiful human being?

java - Error in Python-generated XML - Stack Overflow

java python xml xstream
Rectangle 27 2

If the library is supported on Android, it will work.

Put it in the Core project's "libs" folder. Add it to its Order & Export tab.

Add it to the Libraries tab of the Android Project. ("Add jars", not "Add external jars") And then check it in the Order & Export tab aswell.

That means that projects that depend on the main project will also have gdx.jar on their classpath. However, this doesn't work for Android projects.

This just means that the libraries in the classpath of the Core project aren't automatically added to the Android project (As far as I know, some time ago it did).

If you get the Multiple dex files error. Uncheck private libraries in the Order & Export tab of the Android project.

Libgdx, Transitive dependencies Android,Java library project, Jar - St...

android jar libgdx xstream
Rectangle 27 2

This is caused because Maven and Eclipse are two different building tools, sometimes resembling and sometimes disjoint. So, the M2 plugin is supposed to adapt the POM's contents to the building lifecycle of Eclipse. However, as Maven's building lifecycle is much more complete than Eclipse's, M2 is not always able to do such an adaptation, and in these cases it raises the error you are asking about.

Usually, you should not worry a lot about this, because the project will eventually be built by Maven, so the important thing is the POM be 100% understood by Maven, not Eclipse. We use Eclipse mostly for the automatic building, not for producing the final JAR.

Anyway, you can drop these errors through three alternative options (available in the very screenshots you have posted):

  • Discover new M2 connectors: I do not recommend this, if you are using the latest M2 version. You can give it a try once, if you want.

The other two options are both aimed to instruct Eclipse to ignore the reported plugins:

  • Permanently mark goal X in pom.xml as ignored: It adds an extra declaration to the POM marking that plugin as ignorable by Eclipse.
  • Mark goal X as ignored in Eclipse build: It leaves the POM unmodified, but adds that info to the current Eclipse workspace metadata, so it will be applied to all POMs (present and future) in the same workspace.

java - Maven configuration while building project - Stack Overflow

java eclipse maven xstream
Rectangle 27 2

compile fileTree(dir: 'libs', include: '*.jar')

line. If your libs folder is in core project's folder, add above line to

project(":core") {...

    dependencies {....
        compile fileTree(dir: 'libs', include: '*.jar')
    }
}

part of your build.gradle file. And add below line to your Android project's part in the build.gradle file.

project(":android") {...

    dependencies {....
        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

Android must have this line but it is not necessary for other projects.

Libgdx, Transitive dependencies Android,Java library project, Jar - St...

android jar libgdx xstream
Rectangle 27 6

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));
    }
}

class - How do you make a deep copy of an object in Java? - Stack Over...

java class clone
Rectangle 27 6

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));
    }
}

class - How do you make a deep copy of an object in Java? - Stack Over...

java class clone
Rectangle 27 1

XStream xstream = new XStream();
    xstream.alias("Info", Info.class);
    renderXml(callInfo, xstream);

It's possible to pass XStream instance with special properties. And everything works

java - How to control XML element names in Play framework - Stack Over...

java xml playframework
Rectangle 27 4

I've always had positive experiences with XStream:

As you can see, it's simple to use.

I haven't actually used XStream with Generics (I've only ever used it for simple JavaBean type classes), but Google seems to suggest it handles them without problems. e.g. http://techo-ecco.com/blog/xstream-spring-ws-oxm-and-generics/

n.b. that blog link leads on to talk about using Spring to simplify the outputted xml, but the first xml snippet indicates that plain-old XStream handles the Generic LinkedList nicely

The tutorial itself uses a List<T> so it seems to be working. Therefore the /must have standard constructor/ is fair tradeoff.

xml serialization - Best Practice for Serialize/Deserialize from Java ...

java xml-serialization xml-deserialization
Rectangle 27 1

Unfortunately, per the XSTream FAQ, XStream does not support XML namespaces unless using a StAX parser

Not every XML parser supports namespaces and not every XML parser that supports namespaces can be configured within XStream to use those. Basically namespaces must be supported individually for the different XML parsers and the only support for namespaces that has currently been implemented in XStream is for the StAX paser. Therefore use and configure the StaxDriver of XStream to use namespaces.

sorry but that doesn't tell how to put two different namespaces in .java file , There is only one namespace ns0.

If that question isn't exactly what you want, look through the links in the Related section there. If none of those fit your situation, you should ask a new question rather than extend this conversation in comments. Thanks.

There's already a fine answer there by JAXB master Blaise Doughan. Go with it.

java - Define namespaces tags so that generated XML have those tags? -...

java xml xstream
Rectangle 27 1

Unfortunately, per the XSTream FAQ, XStream does not support XML namespaces unless using a StAX parser

Not every XML parser supports namespaces and not every XML parser that supports namespaces can be configured within XStream to use those. Basically namespaces must be supported individually for the different XML parsers and the only support for namespaces that has currently been implemented in XStream is for the StAX paser. Therefore use and configure the StaxDriver of XStream to use namespaces.

sorry but that doesn't tell how to put two different namespaces in .java file , There is only one namespace ns0.

If that question isn't exactly what you want, look through the links in the Related section there. If none of those fit your situation, you should ask a new question rather than extend this conversation in comments. Thanks.

There's already a fine answer there by JAXB master Blaise Doughan. Go with it.

java - Define namespaces tags so that generated XML have those tags? -...

java xml xstream