I tried to convert xml output to string my code is below:
OAuthRequest request2 = new OAuthRequest(Verb.GET,"https://api.linkedin.com/v1/people/~:(first-name,last-name,email-address)");
request2.addHeader("Authorization", "Bearer "+accesstok);
Response response2 = request2.send();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(response2.getBody());
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
String strFileContent = stringWriter.toString(); //This is string data of xml file
System.out.println(strFileContent);
i am getting the output as below:
java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<first-name>xxxxxxx</first-name>
<last-name>xxxx</last-name>
<email-address>xxxxxxxxxx</email-address>
</person>
how do i extract first-name
Related
I create entity reference with EntityReference ent = doc.createEntityReference(txt). Then I add it to the node: node.appendChild(ent); and the txt is like "lt". So, I expect to see < in my XML file. But all entity references are missing. Other elements are added and shown well, but not EntityReference.
XML is created as:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
dumping to the file:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
return xmlString;
The result XML has a standard header:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
...
Where can be a problem?
I have an xml file, and sometimes I have to delete some nodes.
This is my code:
String xmlProduct = ""; //my xml above
if(!xmlProduct.equals("")){
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlProduct));
Document dom;
DocumentBuilderFactory dbf = (DocumentBuilderFactory) DocumentBuilderFactory.newInstance();
DocumentBuilder db = (DocumentBuilder) dbf.newDocumentBuilder();
dom = db.parse(is);
dom.normalize();
//delete property
NodeList nodoProperty = dom.getDocumentElement().getElementsByTagName("Property");
for(int i=0; i<nodoProperty.getLength(); i++){
Node nodoBorrar = nodoProperty.item(i);
nodoRaizXML.item(0).removeChild(nodoBorrar);
}
}
//Convert to xml format
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(dom), new StreamResult(writer));
This is an example of my xml:
<Deal>
<SelectedDeal>+1</SelectedDeal>
</Deal>
<Property>
<PropertyId>8215</PropertyId>
<HPIValueChanged>1</HPIValueChanged>
</Property>
<FundBooking>
<ProductCode>J128R?</ProductCode>
<ControlNumber> </ControlNumber>
</FundBooking>
And this is what I got when executing:
<Deal>
<SelectedDeal>+1</SelectedDeal>
</Deal>
<FundBooking>
<ProductCode>J128R?</ProductCode>
<ControlNumber> </ControlNumber>
</FundBooking>
the tag is deleted, but I need to delete its space in the file.
How can I do this
This is the quick & dirt solution :
xmlProduct = xmlProduct.replaceAll("\n", "").replaceAll("\r", "");
//...
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
I am trying to read the whole XML file in Java. Below is my XML file-
<?xml version="1.0" encoding="UTF-8"?>
<app hash='nv', name='Tech', package = '1.0', version='13', filesize='200', create_date='01-03-1987', upate_date='07-09-2013' >
<url>
<name>RJ</name>
<score>10</score>
</url>
<url>
<name>ABC</name>
<score>20</score>
</url>
</app>
And below is my code, I am using to read the full XML file as shown above and then get hash, name, package etc value from that XML file.
public static void main(String[] args) {
try {
File fXmlFile = new File("C:\\ResourceFile\\app.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
System.out.println(doc);
} catch (Exception e) {
}
}
And as soon as I am running the above program. I am always getting the below excpetion-
[Fatal Error] app.xml:2:22: Element type "app" must be followed by either attribute specifications, ">" or "/>".
Any idea why it is happening?
If you don't want to parse it as XML and only to show as a String maybe you want to use
a BufferedReader and readLine() store it in a StringBuilder and then show it. How to read a file
Example:
public String readFile(String path) throws IOException{
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(path))){
while ((String sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
}
return sb.toString();
}
EDIT In java 8 you can just simply use
String xml = Files.lines(Paths.getPath(path)).collect(Collectors.joining("\n"));
There is syntax error in your xml. The attributes of the element should not be separated by a comma. It should be like,
<?xml version="1.0" encoding="UTF-8"?>
<app hash='nv' name='Tech' package='1.0' version='13' filesize='200' create_date='01-03-1987' upate_date='07-09-2013' >
<url>
<name>RJ</name>
<score>10</score>
</url>
<url>
<name>ABC</name>
<score>20</score>
</url>
</app>
try{
InputStream is = getAssets().open("HeadWork_JackWell.xml");
DocumentBuilderFactory dFactory= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dFactory.newDocumentBuilder();
Document doc= dBuilder.parse(is);
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
String s=sw.toString();
System.out.println(s);
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
Im trying to create XML document with DOM APi's and when i use the following code I got the
expect result
Element rootTreeNode = document.createElementNS("http://schemas.microsoft.com/ado/2007","ex" + ":Ex")
this is the output with tags in output console
ex:Ex Version="1.0" xmlns:ex="http://schemas.microsoft.com/ado/2007"/
Now I want to add to this element the following
**xmlns:gp**="http://www.pst.com/Protocols/Data/Generic"
and I dont succeed with the xmlns:gp i have tried to use
the like the following
rootTreeNode.setAttributeNS("xmlns" ,"gp","http://www.pst.com/Protocols/Data/Generic")
and i have got it like the folloing
**xmlns:ns0="xmlns"** **ns0:gp**="http://www.pst.com/Protocols/Data/Generic"
and if put null in the first parameter
rootTreeNode.setAttributeNS(null ,"gp","http://www.pst.com/Protocols/Data/Generic")
I get just gp with the URL without the xmlns .
what am i doing wrong here ?
Thanks!!!
Complete test:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElementNS("http://schemas.microsoft.com/ado/2007","ex" + ":Ex");
root.setAttributeNS("http://www.w3.org/2000/xmlns/" ,"xmlns:gp","http://www.pst.com/Protocols/Data/Generic");
doc.appendChild(root);
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
System.out.println("Xml:\n\n" + xmlString);
I am using the follwing code to change a xml document:
DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
fty1.setNamespaceAware(true);
DocumentBuilder builder1 = fty1.newDocumentBuilder();
ByteArrayInputStream bais1 = new ByteArrayInputStream(tr1.getBytes());//tr1=xml string
Document xmldoc1=builder1.parse(bais1);
xmldoc1.getElementsByTagName("userID").item(0).setTextContent("123123132");
The xmldoc1 contains the changed form. Now how convert it to a string so that the new doument can be passed to others.
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xmldoc1);
transformer.transform(source, result);
String xmlString = sw.toString();