I'm following this article to get the contents of a iTunes playlist
The author says the following XSL can be used to transform a named iTunes playlist into M3U format:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:param name="playlist" />
<xsl:variable name="newline">
<xsl:text>
</xsl:text>
</xsl:variable>
<xsl:template match="/">
<xsl:for-each select="plist/dict/key[text()='Playlists']/
following-sibling::array/dict/key[text()='Name']/
following-sibling::string[text()=$playlist]/
following-sibling::key[text()='Playlist Items']/
following-sibling::array/dict">
<xsl:call-template name="track">
<xsl:with-param name="trackid" select=
"key[text()='Track ID']/following-sibling::integer" />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="track">
<xsl:param name="trackid" />
<xsl:variable name="url"
select="//plist/dict/key[text()='Tracks']/
following-sibling::dict/dict/key[text()='Track ID']/
following-sibling::integer[text()=$trackid]/../
key[text()='Location']/following-sibling::string" />
<xsl:value-of select="$url" /><xsl:value-of select="$newline" />
</xsl:template>
</xsl:stylesheet>
How can I do that? From what I learned so far about XSL I thought I might have to replace $playlist with the the playlist's name. Am I right? And if yes, how can I do that efficiently as addition to the following code:
public String getPlaylist(String playlist) {
Source source = new StreamSource(library);
StreamSource xsl = new StreamSource(getClass().getResourceAsStream("M3Utransformation.xml"));
StringWriter w = new StringWriter();
Result result = new StreamResult(w);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
transformer.transform(source, result);
return w.getBuffer().toString();
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
Transformer has an API to pass in parameter values, you just need to add
transformer.setParameter("playlist", playlist);
immediately before the transformer.transform(...) line.
If you're going to be calling this method repeatedly then rather than loading and compiling the stylesheet every time it would be more efficient to load it once and then re-use the same Transformer for future calls:
private Transformer transformer = null;
public String getPlaylist(String playlist) {
if(transformer == null) {
StreamSource xsl = new StreamSource(getClass().getResourceAsStream("M3Utransformation.xml"));
try {
transformer = TransformerFactory.newInstance().newTransformer(xsl);
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
StringWriter w = new StringWriter();
Source source = new StreamSource(library);
Result result = new StreamResult(w);
try {
transformer.setParameter("playlist", playlist);
transformer.transform(source, result);
return w.getBuffer().toString();
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
(Note that Transformer is not thread safe, so if you're making calls from multiple threads you'd need to use the Templates mechanism instead)
Related
I have a pretty big xml file and need to change some of it, this is a snippet of how it looks
<CMPDN>
<ROOT_PRODUKTE>
<PRODUKT name="00010000040">
<BEZIEHUNGEN>
<BEZIEHUNGSTYP name="ZBH2BIKE">
<PRODUKT name="78104974100" id="1001049290">
<RELATEDARTICLES>
<RELATEDARTICLE name="F6101M0" id="1000264817"/>
</RELATEDARTICLES>
</PRODUKT>
</BEZIEHUNGSTYP>
</BEZIEHUNGEN>
</PRODUKT>
</ROOT_PRODUKTE>
This is as said just a snippet.
I used jxb to convert a xsd file into java classes so now I was able to modify the data.
The problem comes when I want to rename one of the tags, and not just any tag. I want to rename the inner PRODUKT tag to PRODUKT_FIT like this:
<CMPDN>
<ROOT_PRODUKTE>
<PRODUKT name="00010000040">
<BEZIEHUNGEN>
<BEZIEHUNGSTYP name="ZBH2BIKE">
<PRODUKT_FIT name="78104974100" id="1001049290">
<RELATEDARTICLES>
<RELATEDARTICLE name="F6101M0" id="1000264817"/>
</RELATEDARTICLES>
</PRODUKT_FIT>
</BEZIEHUNGSTYP>
</BEZIEHUNGEN>
</PRODUKT>
</ROOT_PRODUKTE>
Now I have tried to create 3 new classes BEZIEHUNGEN,BEZIEHUNGSTYPand PRODUKT_FIT and I changed the definition for the class PRDUKT as seen here
public class PRODUKT {
#XmlElements({
#XmlElement(name = "ATTRIBUTE", type = ATTRIBUTE.class),
#XmlElement(name = "BEZIEHUNGEN", type = io.github.sumsar1812.models.write.BEZIEHUNGEN.class),
#XmlElement(name = "BEZIEHUNGEN", type = BEZIEHUNGEN.class),
#XmlElement(name = "KLASSEN", type = KLASSEN.class),
#XmlElement(name = "LAENDER", type = LAENDER.class),
#XmlElement(name = "MEDIENELEMENTE", type = MEDIENELEMENTE.class),
#XmlElement(name = "PREISE", type = PREISE.class),
#XmlElement(name = "RELATEDARTICLES", type = RELATEDARTICLES.class),
#XmlElement(name = "TEXTELEMENTE", type = TEXTELEMENTE.class),
#XmlElement(name = "PARENT_NAME", type = PARENTNAME.class),
})
where the models.write package contains the new 3 classes.
The PRODUKT_FIT class is shown below:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"attributeOrBEZIEHUNGENOrKLASSEN"
})
#XmlRootElement(name = "PRODUKT_FIT")
public class PRODUKT_FIT {
#XmlElements({
#XmlElement(name = "ATTRIBUTE", type = ATTRIBUTE.class),
#XmlElement(name = "BEZIEHUNGEN", type = io.github.sumsar1812.models.write.BEZIEHUNGEN.class),
#XmlElement(name = "KLASSEN", type = KLASSEN.class),
#XmlElement(name = "LAENDER", type = LAENDER.class),
#XmlElement(name = "MEDIENELEMENTE", type = MEDIENELEMENTE.class),
#XmlElement(name = "PREISE", type = PREISE.class),
#XmlElement(name = "RELATEDARTICLES", type = RELATEDARTICLES.class),
#XmlElement(name = "TEXTELEMENTE", type = TEXTELEMENTE.class)
})
protected List<Object> attributeOrBEZIEHUNGENOrKLASSEN;
#XmlAttribute(name = "name", required = true)
protected String name;
/*getters and setters omitted */
So as far as I can see now a produkt should be able to contain both the read values of BEZIEHUNGEN and write values of BEZIEHUNGEN(containing a list of BEZIEHUNGSTYP and each of those containing a list of PRODUKT_FIT)
After reformatting some data I can see with the debugger that the data is formated correctly(RELATEDARTICLE is optional so thats why attributeOrBEZIEHUNGENOrKLASSEN is null)
But the problem is when i try to save the classes back to a file(as seen below) it is still named PRODUKT and not PRODUKT_FIT, all the other changes i have made to the data is saved correctly. any idea why this is ?
public void passRoot(String newFilename, CMPDN root) {
try {
File file = new File(newFilename);
JAXBContext jaxbContext = JAXBContext.newInstance(CMPDN.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
jaxbMarshaller.marshal(root, file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
Edit
So I tried using XSLT with some success, this is my stylesheet right now
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8"/>
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="CMPDN/ROOT_PRODUKTE/PRODUKT/BEZIEHUNGEN/BEZIEHUNGSTYP/PRODUKT">
<PRODUKT_FIT>
<xsl:apply-templates select="#*|node()" />
<xsl:value-of select="."/>
</PRODUKT_FIT>
</xsl:template>
This works but it adds blank lines below /RELATEDARTICLES> and </PRODUKT_FIT> So I tried adding <xsl:strip-space elements="*"/> but that made it all into one line, so I added omit-xml-declaration="yes" indent="yes" to the xsl:output but this only partly fixed it as now it looks like this:
which doesnt have the format as before, not sure why though?
Use this in your stylesheet file:
<xsl:output method="xml" omit-xml-declaration="yes"
indent="yes" encoding="utf-8" xslt:indent-amount="3"
xmlns:xslt="http://xml.apache.org/xslt" />
<xsl:strip-space elements="*" />
Of course, you can configure the indent-amount according to your needs.
See Apache Xalan for further info.
I have a xml file where I would like to fill in values from another xml file. For example, if I have data.xml:
<Data>
<Person>
<Name>neby</Name>
<Phone>
<Home>5553456789</Home>
<Mobile>5559879876</Mobile>
</Phone>
</Person>
</Data>
I want to fill in test.xml like this (Data taken from the above file):
<Test>
<Name>${Name}</Name>
<Number>${Home}</Number>
</Test>
In my Java program, I create XML files during runtime. I would like to give a file name, "pass" it to test.xml, have test.xml read it, and fill in the text.
Is there a way to do this?
Am I doing it correctly? All I get is the encoding. Never mind, I got it to work. Using the data.xml from above.
MyXSL.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="Data/Person">
<Test>
<Name><xsl:value-of select="Name"/></Name>
<Number><xsl:value-of select="Home"/></Number>
</Test>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Code:
try {
File stylesheet = new File("MyXSL.xsl");
File dataFile = new File("data.xml");
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(dataFile);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
System.out.println(stringWriter.toString());
} catch(Exception e){
e.printStackTrace();
}
Output: <?xml version="1.0" encoding="UTF-8"?>
What am I doing wrong? Above code works.
Create XSLT and then something like that (very simple from oracle java tuts):
// ...
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
// ...
public class Stylizer {
// ...
public static void main (String argv[]) {
// ...
try {
File stylesheet = new File(argv[0]);
File datafile = new File(argv[1]);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(datafile);
// ...
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = Factory.newTransformer(stylesource);
}
}
}
All informations and step-by-step guide to create XSLT and this sample app is here.
I have written a program to find all XML files matching a particular pattern in a directory and modify it by adding a new tag.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<paths>
<upgradepath startversion="1.4.0.0" moduleid="${moduleId}" endversion="1.4.0.1">
<steps>
<!-- Put scripts here to go from 1.4.0.0 to 1.4.0.1 -->
</steps>
</upgradepath>
<upgradepath startversion="1.4.0.1" moduleid="${moduleId}" endversion="1.4.0.2">
<steps>
<!-- Put scripts here to go from 1.4.0.1 to 1.4.0.2 -->
</steps>
</upgradepath>
</paths>
After running my program the XML file gets modified as below :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<paths>
<upgradepath endversion="1.4.0.1" moduleid="${moduleId}" startversion="1.4.0.0">
<steps>
<!-- Put scripts here to go from 1.4.0.0 to 1.4.0.1 -->
</steps>
</upgradepath>
<upgradepath endversion="1.4.0.2" moduleid="${moduleId}" startversion="1.4.0.1">
<steps>
<!-- Put scripts here to go from 1.4.0.1 to 1.4.0.2 -->
</steps>
</upgradepath>
<upgradepath endversion="1.4.0.3" moduleid="${moduleId}" startversion="1.4.0.2">
<steps>
<!--Put scripts here to go from 1.4.0.2 to 1.4.0.3-->
</steps>
</upgradepath>
</paths>
If you see the attributes of all the tags you will see that they have all been rearranged in ascending order. The startversion attribute now appears last and the endversion attribute appears first. I want the original order of the attributes after modification of the XML file. I have tried almost everything and have lost all hope. Is there any way I can do this? Also is there a way to sort the attributes in descending order? It's not the right solution but it helps.
Here is a code snippet from the program I am using to modify the files :
private static void updateXMLFiles(String sStartVersion, String sEndVersion) {
try {
for (int c = 0; c < pathsList.size(); c++) {
File xmlFile = new File(pathsList.get(c).toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
// Get the last <upgradepath> tag in the file.
// Method Call to verify the version entered and update the XML Files.
// Write the updated document to the file.
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(pathsList.get(c).toString()));
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
}
catch (SAXException e1) {
e1.printStackTrace();
}
catch (ParserConfigurationException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
catch (TransformerException e1) {
e1.printStackTrace();
}
}
private static void addNewVersion(Document doc, String sStartVersion, String sEndVersion) {
Element element = doc.getDocumentElement();
Element upgradePath = doc.createElement("upgradepath");
upgradePath.setAttribute("startversion", sStartVersion);
upgradePath.setAttribute("moduleid", "${moduleId}");
upgradePath.setAttribute("endversion", sEndVersion);
Element steps = doc.createElement("steps");
Comment comment = doc.createComment("Put scripts here to go from " + sStartVersion + " to " + sEndVersion);
steps.appendChild(comment);
upgradePath.appendChild(steps);
element.appendChild(upgradePath);
}
Is there any way I can keep the order of the attributes intact or in the worst case arrange it in descending order?
A friend of mine suggested I try out JAXB but I couldn't find a way to achieve this. If someone thinks JAXB can solve this do mention how to format an existing XML file and not creating one.
Another issue which is not a major concern is that although I have used the
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
the newly added tags are not indented correctly. Any way to fix this?
#XmlType(propOrder = {"startversion", "moduleid", "endversion", "steps"})
public class XmlSubModel {
private String startversion = "";
private String moduleid = "";
private String endversion = "";
private String steps = "";
#XmlAttribute
public String getStartversion() {
return startversion;
}
public void setStartversion(String startversion) {
this.startversion = startversion;
}
#XmlAttribute
public String getModuleid() {
return moduleid;
}
public void setModuleid(String moduleid) {
this.moduleid = moduleid;
}
#XmlAttribute
public String getEndversion() {
return endversion;
}
public void setEndversion(String endversion) {
this.endversion = endversion;
}
public String getSteps() {
return steps;
}
public void setSteps(String steps) {
this.steps = steps;
}
}
I use Jaxb2 and Spring. I am trying to unmarshal some XML that are sent by 2 of my customers.
Up to now, I only had to handle one customer which sent some xml like this :
<foo xmlns="com.acme">
<bar>[...]</bar>
<foo>
that is bound to a POJO like this :
#XmlType(name = "", propOrder = {"bar"})
#XmlRootElement(name = "Foo")
public class Foo {
#XmlElement(name = "Bar")
private String bar;
[...]
}
I discovered that the previous developer hardcoded the namespace in the unmarshaller in order to make it work.
Now, the second customer sends the same XML but changes the namespace!
<foo xmlns="com.xyz">
<bar>[...]</bar>
<foo>
Obviously, the unmarshaller fails to unmarshall because it expects some {com.acme}foo instead of {com.xyz}foo. Unforunately, asking the customer to change the XML is not an option.
What I tried :
1) In application-context.xml, I searched for a configuration which would allow me to ignore the namespace but could not find one :
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan">
<list>
<value>com.mycompany.mypkg</value>
</list>
</property>
<property name="marshallerProperties">
<map>
<entry key="???"><value type="java.lang.Boolean">false</value></entry>
</map>
</property>
</bean>
it seems that the only available options are the ones listed in the Jaxb2Marshaller's Javadoc :
/**
* Set the JAXB {#code Marshaller} properties. These properties will be set on the
* underlying JAXB {#code Marshaller}, and allow for features such as indentation.
* #param properties the properties
* #see javax.xml.bind.Marshaller#setProperty(String, Object)
* #see javax.xml.bind.Marshaller#JAXB_ENCODING
* #see javax.xml.bind.Marshaller#JAXB_FORMATTED_OUTPUT
* #see javax.xml.bind.Marshaller#JAXB_NO_NAMESPACE_SCHEMA_LOCATION
* #see javax.xml.bind.Marshaller#JAXB_SCHEMA_LOCATION
*/
public void setMarshallerProperties(Map<String, ?> properties) {
this.marshallerProperties = properties;
}
2) I also tried to configure the unmarshaller in the code :
try {
jc = JAXBContext.newInstance("com.mycompany.mypkg");
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);//Tried this option.
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile.toFile());
u.unmarshal(new DOMSource(doc));
return (Foo)u.unmarshal(new StreamSource(xmlFile.toFile()));
} catch (ParserConfigurationException | SAXException | IOException | JAXBException e) {
LOGGER.error("Erreur Unmarshalling CPL");
}
3) Different form with a SAXParser :
try {
jc = JAXBContext.newInstance("com.mycompany.mypkg");
Unmarshaller um = jc.createUnmarshaller();
final SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false);
final XMLReader reader = sax.newSAXParser().getXMLReader();
final Source er = new SAXSource(reader, new InputSource(new FileReader(xmlFile.toFile())));
return (Foo)um.unmarshal(er);
}catch(...) {[...]}
This one works! But still, I would prefer to be able to autowire the Unmarshaller without needing this ugly conf everytime.
Namesapce awareness is feature of the document reader/builder/parser not marshallers. XML elements from different namespaces represents different entities == objects, so marshallers cannot ignore them.
You correctly switched off the namespaces in your SAX reader and as you said it worked. I don't understand your problem with it, your marshaller still can be injected, the difference is in obtaining the input data.
The same trick with document builder should also work (I will test it later on), I suspect that you were still using the marshaller with "hardcoded" namespace but your document was namespace free.
In my project I use XSLT to solve similar issue. Setting namespace awarness is definitely easier solution. But, with XSLT I could selectviely remove only some namespaces and also my my input xml are not always identical (ignoring namespaces) and sometimes I have to rename few elements so XSLT gives me this extra flexibility.
To remove namespaces you can use such xslt template:
<xsl:stylesheet version="1.0" xmlns:e="http://timet.dom.robust.ed" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:template match="/">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="#* | node()" />
</xsl:element>
</xsl:template>
<xsl:template match="#*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<xsl:template match="text() | processing-instruction() | comment()">
<xsl:copy />
</xsl:template>
</xsl:stylesheet>
Then in Java before unmarshalling I transform the input data:
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
Source source = new DOMSource(xml);
DOMResult result = new DOMResult();
transformer.transform(source, result);
Thank you all, here shared my solution which works for my code , i try to make it generic every namespace contain ": " i write code if any tag have ":" it will remove from xml , This is used to skip namespace during unmarshalling using jaxb.
public class NamespaceFilter {
private NamespaceFilter() {
}
private static final String COLON = ":";
public static XMLReader nameSpaceFilter() throws SAXException {
XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
private boolean skipNamespace;
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (qName.indexOf(COLON) > -1) {
skipNamespace = true;
} else {
skipNamespace = false;
super.startElement("", localName, qName, atts);
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.indexOf(COLON) > -1) {
skipNamespace = true;
} else {
skipNamespace = false;
super.endElement("", localName, qName);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (!skipNamespace) {
super.characters(ch, start, length);
}
}
};
return xr;
}
}
for unmarshalling
XMLReader xr = NamespaceFilter.nameSpaceFilter();
Source src = new SAXSource(xr, new InputSource("C:\\Users\\binal\\Desktop\\response.xml"));
StringWriter sw = new StringWriter();
Result res = new StreamResult(sw);
TransformerFactory.newInstance().newTransformer().transform(src, res);
JAXBContext jc = JAXBContext.newInstance(Tab.class);
Unmarshaller u = jc.createUnmarshaller();
String done = sw.getBuffer().toString();
StringReader reader = new StringReader(done);
Tab tab = (Tab) u.unmarshal(reader);
System.out.println(tab);
`
I've followed Java docs to handle namespace in xml while unmarshalling, it did the trick.
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File( "nosferatu.xml"));
//If just a string
//InputSource is = new InputSource(new StringReader(line));
//Document doc = db.parse(is)
Object o = u.unmarshal( doc );
Used Java API JAXB Context and Unmarshal features.
https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/Unmarshaller.html
I am trying to send xml file to server after processing it which has some special character like "佥佬佧佼A£".
Currently code looks like
public class Utils {
public static String transformToString(Document activeDocument) throws TransformerException{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "true");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
writer.toString();
}
Test class
public class Test {
public static void main(String[] args){
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath);
//Doing some process on doc and changing other values
String xmlString = Utils.transformToString(doc);
// Sending xml to soap
HttpPost post = new HttpPost(endpoint);
post.setEntity(new StringEntity(xmlString));
post.setHeader(new BasicHeader("content-type", "text/xml"));
.................
}
}
XML file
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope ....>
<soapenv:Header/>
<soapenv:Body>
<Test>
<Id>佥佬佧佼A£</Id>
..............
..........
</Test>
.........
I am getting xmlString with Id value : ????A£
What I want is : 佥佬佧佼A£
How can I do that ? I just want String format of that XML.
EDIT : I am loading one XML, Doing some changes into it, and sending that XML to SOAP, by Setting that document to httpPost.setEntity()
Thanks,
Ankit
You can try:
encoding="UTF-16"
instead of
encoding="UTF-8"