Changing XML values in Android/Java - java

I want to take an XML file as input which contains the following:
<?xml version='1.0' encoding='utf-8' standalone='yes'>
<map>
<int name="count" value="10" />
</map>
and, read and change the value from 10 to any other integer value.
How can I do this in Android/Java. I'm new to Android and Java and all the tutorials available on the internet are way too complicated.
Thank You

You can change the value by matching the pattern and replacing the string as like below,
String xmlString = "<int name=\"count\" value=\"10\" />";
int newValue = 100;
Pattern pattern = Pattern.compile("(<int name=\"count\" value=\")([0-9]{0,})(\" />)");
Matcher matcher = pattern.matcher(xmlString);
while (matcher.find()) {
String match = matcher.group(2);
xmlString = xmlString.replace(match, String.valueOf(newValue));
}
System.out.println(xmlString);

You can find your answer here. It is like parsing json. You can cast your string(from file) to object and do anything with parameters

Related

Parsing HTTP XML Response Using Regex In Java

I am making an API call and now I need to get a specific piece of data from the response. I am needing to get the DocumentID for the "Description" Invoice, which in the case below is 110107.
I have already created a method to get data from get a single tag by doing this:
public synchronized String getTagFromHTTPResponseAsString(String tag, String body) throws IOException {
final Pattern pattern = Pattern.compile("<"+tag+">(.+?)</"+tag+">");
final Matcher matcher = pattern.matcher(body);
matcher.find();
return matcher.group(1);
} // end getTagFromHTTPResponseAsString
However, my problem is with this result set, there are multiple fields with the same tag and I need a specific one. Here is the response:
<?xml version="1.0" encoding="utf-8"?>
<Order TrackingID="351535" TrackingNumber="TEST-843245" xmlns="">
<ErrorMessage />
<StatusDocuments>
<StatusDocument NUM="1">
<DocumentDate>7/14/2017 6:52:00 AM</DocumentDate>
<FileName>4215.pdf</FileName>
<Type>Sales Contract</Type>
<Description>Uploaded Document</Description>
<DocumentID>110098</DocumentID>
<DocumentPlaceHolder />
</StatusDocument>
<StatusDocument NUM="2">
<DocumentDate>7/14/2017 6:52:00 AM</DocumentDate>
<FileName>Apex_Shortcuts.pdf</FileName>
<Type>Other</Type>
<Description>Uploaded Document</Description>
<DocumentID>110100</DocumentID>
<DocumentPlaceHolder />
</StatusDocument>
<StatusDocument NUM="3">
<DocumentDate>7/14/2017 6:52:00 AM</DocumentDate>
<FileName>CRAddend.pdf</FileName>
<Type>Other</Type>
<Description>Uploaded Document</Description>
<DocumentID>110104</DocumentID>
<DocumentPlaceHolder />
</StatusDocument>
<StatusDocument NUM="4">
<DocumentDate>7/14/2017 6:52:00 AM</DocumentDate>
<FileName>test.pdf</FileName>
<Type>Other</Type>
<Description>Uploaded Document</Description>
<DocumentID>110102</DocumentID>
<DocumentPlaceHolder />
</StatusDocument>
<StatusDocument NUM="5">
<DocumentDate>7/14/2017 6:55:00 AM</DocumentDate>
<FileName>Invoice.pdf</FileName>
<Type>Invoice</Type>
<Description>Invoice</Description>
<DocumentID>110107</DocumentID>
<DocumentPlaceHolder />
</StatusDocument>
</StatusDocuments>
</Order>
I tried creating and testing out my regular expression on https://regex101.com/ and got this RegEx to work there, but I cannot get it to translate over correctly into my Java code:
<Description>Invoice<\/Description>
<DocumentID>(.*?)<\/DocumentID>
Try it with Jsoup
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class sssaa {
public static void main(String[] args) throws Exception {
String xml = "yourXML";
Document doc = Jsoup.parse(xml);
Elements StatusDocuments = doc.select("StatusDocument");
for(Element e : StatusDocuments){
if(e.select("Description").text().equals("Invoice")){
System.out.println(e.select("DocumentID").text());
}
}
}
}
What I have done to solve this is use StringBuilder to convert the response into a single string and then used this piece of code to get the DocumentID:
// Create the pattern and matcher
Pattern p = Pattern.compile("<Description>Invoice<\\/Description><DocumentID>(.*)<\\/DocumentID>");
Matcher m = p.matcher(responseText);
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println("group0 = " + m.group(0)); // whole matched expression
System.out.println("group1 = " + m.group(1)); // first expression from round brackets (Testing)
}
// Set the documentID for the Invoice
documentID = m.group(1);
Looks like this is probably not the best way to go about doing this, but it is working for now. I will come back and try to clean this up with a more correct solution from suggestions given here.

RSS Feed - Parse/Extract src image tag inside Description tag in JAVA

Extending this question
How to extract an image src from RSS feed
for JAVA, answer is already made for ios, but to make it work in JAVA there is not enough solutions made for it.
RSS Feeds parsing the direct tag is known for me, but parsing tag inside another tag is quite complicated like this below
<description>
<![CDATA[
<img width="745" height="410" src="http://example.com/image.png" class="attachment-large wp-post-image" alt="alt tag" style="margin-bottom: 15px;" />description text
]]>
</description>
How to split up the src tag alone?
Take a look at jsoup. I think it's what you need.
EDIT:
private String extractImageUrl(String description) {
Document document = Jsoup.parse(description);
Elements imgs = document.select("img");
for (Element img : imgs) {
if (img.hasAttr("src")) {
return img.attr("src");
}
}
// no image URL
return "";
}
You could try to use a regular expression to get the value,
give a look to this little example, I hope it's help you.
For more info about regular expression you can find more info here.
http://www.tutorialspoint.com/java/java_regular_expressions.htm
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test{
public static void main(String []args){
String regularExpression = "src=\"(.*)\" class";
String html = "<description> <![CDATA[ <img width=\"745\" height=\"410\" src=\"http://example.com/image.png\" class=\"attachment-large wp-post-image\" alt=\"alt tag\" style=\"margin-bottom: 15px;\" />description text ]]> </description>";
// Create a Pattern object
Pattern pattern = Pattern.compile(regularExpression);
// Now create matcher object.
Matcher matcher = pattern.matcher(html);
if (matcher.find( )) {
System.out.println("Found value: " + matcher.group(1) );
//It's prints Found value: http://example.com/image.png
}
}
}

XStream apostrophe Issue in converting Java Object to XML

I am using com.thoughtworks.xstream.XStream to Generate xml String. I parse Object to xstream.toXML method and I get the xml output according to the way I need.
<myxml>
<test type="test" name="test">
<question id="Name" answer="Micheal"/>
<question id="Address" answer="Home">
<details name="First Address">
<detailanswer>friend&apos;s House</detailanswer>
</details>
</basequestion>
</test>
</myxml>
XStream xstream = new XStream();
xstream.alias("myxml", MyXml.class);
xstream.alias("test", Test.class);
xstream.alias("question", Question.class);
xstream.alias("details", Details.class);
xstream.alias("detailanswer", String.class);
xstream.addImplicitCollection(MyXml.class, "test");
xstream.addImplicitCollection(Test.class, "question");
xstream.addImplicitCollection(Question.class, "details");
xstream.addImplicitCollection(Details.class, "detailanswer");
xstream.useAttributeFor(Test.class, "type");
xstream.useAttributeFor(Test.class, "name");
xstream.useAttributeFor(Question.class, "id");
xstream.useAttributeFor(Question.class, "answer");
xstream.useAttributeFor(Details.class, "name");
return xstream.toXML(eform);
Following is the Object structure.
Inside MyXml there is List<Test>
Test has List<Question>, String type, String name
Question has List<Details>, String id, String answer.
Details has List<String> detailAnswer, String name
So the element in the question, Friend's house is added to the List detailAnswer in Details class.
I get friend&apos;s House instead of friend's house. How can I resolve this. Is there special way to convert using XStream?
I think its better to use java method to replace a character.
xStream.toXML(testPojo).replaceAll("&apos;", "'")

extract element from xml string

<media:thumbnail url="http:// mysite.com/wp-content/uploads/2013/11/mes1-300x186.png" width="320" length="125399" type="image/jpg"/>
How to extract the URL from this xml ? If I have the above as string ?
Supposing you have the XML string stored in String str, one lazy and simple way to retrieve the URL (if you always expect the same input text format) could be:
String url = str.split("\"")[1];
Some times, as a quick "one time solution" you can use regular expressions.
String xml="<media:thumbnail url=\"http:// mysite.com/wp-content/uploads/2013/11/ mes1-300x186.png\" width=\"320\" length=\"125399\" type=\"image/jpg\"/>";
Pattern pattern=Pattern.compile("url\\s*=\\s*\\\"(.*?)\\\"");
Matcher m=pattern.matcher(xml);
if(m.find()){
String urlValue=m.group(1);
System.out.println(urlValue);
}

Java Matcher Class

I need a pattern matcher to get the page id value in the below text which is coming from a http response body.
<meta name="ajs-page-id" content="262250">
What i'm after is to get the content value from this line that will always be generated in responsebody.
Pattern pat = Pattern.compile("<meta\\sname=\"ajs-page-id\"\\scontent=\"(\\d+)\">");
That is obviously a very literal pattern... but group(1) should return the number as a string.
Haven't tested.
Use an HTML parser like jsoup to parse and search for the part. You should not be using regular expressions for this.
e.g.,
String htmlStr = "<meta name=\"ajs-page-id\" content=\"262250\">";
Document doc = Jsoup.parse(htmlStr);
Element meta = doc.select("meta[name=ajs-page-id]").first();
if (meta != null)
{
System.out.println(meta.attr("content"));
}

Categories