Sandip Armal Patil
Sandip Armal Patil

Reputation: 5895

Ampersand in URL makes XML not well formed?

I am trying to save xml data in .xml file on AWS S3. So I am building xml in string and passing to aws. File is written but xml data have some url's and it showing Xml Parsing Error: Not Well formed on that url.

Please see following images.

enter image description here

enter image description here

It giving me error new = but second one not first one. If I encode url then it work but I don't want to encode url because I need to decode at every places.

Here is my code.

        // create header for graphml
        String str = "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\""
                + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                + " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns"
                + " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">"
                + "<key id=\"n\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>"                    
                + "<graph id=\"G\" edgedefault=\"directed\">";
        StringBuilder sb = new StringBuilder();
        sb.append(str);

        Iterable<Node> vertices;

        vertices = Node_list;
        // Write all nodes
        for (Node vertex : vertices) {
            sb.append("<node id=" + "\"" + vertex.getId().toString() + "\""
                    + ">");             
                sb.append("<data key=\"n\">" + vertex.getName() + "</data>");               

            // end node tag
            sb.append("</node>");
        }           

        // closing graph tag and graphml tag
        sb.append("</graph>");
        sb.append("</graphml>");            
        // converting string in to inputstream
        InputStream stream = new ByteArrayInputStream(sb.toString()
                .getBytes("UTF-8"));
        // creating meta data graphml file
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("text/xml");
        metadata.setContentLength(sb.toString().getBytes().length);
        // send request to S3 to create folder
        PutObjectRequest putobjreq = new PutObjectRequest(
                CAWSConstants.BUCKETNAME, file, stream, metadata);
        // put graphml file to aws
        s3Client.putObject(putobjreq);

Can you please give me any reference or hint. Xml should get write correctly without encoding/decoding.

Upvotes: 3

Views: 1494

Answers (2)

kjhughes
kjhughes

Reputation: 111706

You have to replace & with &amp; in the URL because & alone has special meaning in XML as the first character of an entity reference.

Upvotes: 6

Martin Honnen
Martin Honnen

Reputation: 167716

In general, don't try to build XML through string concatenation, use a dedicated API like one of the various tree based APIs available in Java (DOM, XOM, JDOM) or https://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLStreamWriter.html.

Upvotes: 2

Related Questions