I have an XML document, that looks like this (I know, it doesn't make sense, it's just an example):
<Person>
<Name>Peter</Name>
<Country>Sweden</Country>
<Param name="Sport" value="yes"/>
<Param name="Color" value="no"/>
<Person/>
It can have an infinit number of the element Param.
Getting the content of Country I do
String country = doc.getElementsByTagName("Country").item(0).getTextContent();
Getting the content of the first attribute name of the first Param I do
String name = source.getElementsByTagName("Param").item(0).getAttributes().item(0).getNodeValue();
But how can I get all values of all the attributes of Param, without knowing how many elements of Param exist?
I need something like ("pseudo code"):
HashMap<String, String> hm = new HashMap<String, String>();
for(int i=0; i<=source.getElementsByTagName("Param").size(); i++){
String name = source.getElementsByTagName("Param").item(i).getAttributes().item(0).getNodeValue();
String value = source.getElementsByTagName("Param").item(i).getAttributes().item(1).getNodeValue();
hm.put(name, value);
}
You can ask for an attribute by its name.
String attrName = source.getElementsByTagName("Param").item(i).getAttribute("name"));
String value = source.getElementsByTagName("Param").item(i).getAttribute("value"));
//you could test if the values are null
hm.put(attrName, value);
HashMap<String, String> hm = new HashMap<String, String>();
SAXReader reader = new SAXReader();
Document document = reader.read("yourxmlfilehere(url, file)");
root = document.getRootElement();
root = root.element("Person");
for(Iterator i = root.elementIterator("Param"); i.hasNext();)
{
Element e = (Element)i.next();
hm.put(e.attributeValue("name"), e.attributeValue("value"));
}
Related
i read the following link that explains to use placeholders by means of expression attribute name
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeValues
My json document is stored as follows:
{"user_json": {"profile.title":"abc"} }"
my java code is as follows
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#u1", "user_json.profile.title");
String projectionExpression = "user_id, #u1";
QuerySpec spec = new QuerySpec()
.withProjectionExpression(projectionExpression)
.withKeyConditionExpression("user_id = :v_id")
.withNameMap(expressionAttributeNames)
.withValueMap(new ValueMap()
.withString(":v_id", userId))
.withConsistentRead(true);
ItemCollection<QueryOutcome> items = table.query(spec);
Iterator<Item> iterator = items.iterator();
String jsonPretty="";
while (iterator.hasNext()) {
jsonPretty = iterator.next().toJSON();
System.out.println(jsonPretty);
}
Problem: not able to retrieve Document path which has a dot in it.
can someone please point out the problem? thanks
Try doing like this:
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#u1_1", "user_json");
expressionAttributeNames.put("#u1_2", "profile.title");
String projectionExpression = "user_id, #u1_1.#u1_2";
I have a json data, And I want to sort it in java. For every category that is not existing, I want to create a new List. after that or if the category exists, I want to add the data "desc" "title" "link1" and "link2" to it.
if (jsonStr != null) try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray products = jsonObj.getJSONArray("Products");
// looping through All products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String category = c.getString("category");
String title = c.getString("title");
String desc = c.getString("desc");
String link1 = c.getString("link1");
String link2 = c.getString("link2");
// tmp hash map for single contact
// HashMap<String, String> contact = new HashMap<>();
List<String> Product = new ArrayList<>();
// adding each child node to HashMap key => value
Product.add(category);
Product.add(title);
Product.add(desc);
Product.add(link1);
Product.add(link2);
if (!categories.contains(category)) {
List<List<String>> [category] = new ArrayList<>(); //here I want to create the name of the new list dynamically if it's not existing yet
}
[category].add(Product);
// adding contact to contact list
categories.add([category]); // and finally adding the category to the categories list ( List<List<List<String>>>)
}
You need to add your new category ArrayList to your categories and keep a reference on it. You can use the handy method of get() from the Map to hit two flies with one stone e.g. something like this
List<List<String>> yourCategoryList = null;
if((yourCategoryList = categories.get(category)) == null){
yourCategoryList = new ArrayList<>();
categories.put(category, yourCategoryList );
}
yourCategoryList.add(product);
I am using a file that consists of:
"word","wordtype","definition"
"Base","n.","The lower part of a robe or petticoat."
"Base","n.","An apron."
The output is as follows:
key: "base" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
key: "word" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
Desired outcome:
key: "base" value: [ "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
key: "word" value: ["word""wordtype""definition"]
Can someone point me in the right direction?
BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(file)));
String line = null;
TreeMap<String, List<String>> def = new TreeMap<String, List<String>>();
List<String> values = new ArrayList<String>();
try {
while ((line = br.readLine()) != null) {
String []parts =line.split(",");
String key = null;
for (int i = 0; i < parts.length; i++){
key = parts[0];
}
values.add(parts[0] + parts[1] + parts[2]);
def.put(key.toLowerCase(), values);
}
A Map cannot work as you request. Any key can only be mapped to a single value.
If you want something akin to what you're doing, but where you can have multiple values for a given key, you could do something like:
List<Map.Entry<String, List<String>>> def = new ArrayList<>();
Map.Entry<String, List<String>> entry = new AbstractMap.SimpleEntry<>(key, list);
def.add(entry);
Then iterate through your def:
for (Map.Entry<String, List<String>> entry : def) {
System.out.println(String.format("Key: %s. Values: %s",
entry.getKey(),
Arrays.toString(entry.getValue().toArray())));
}
Edit:
For your comment: If you want that, you can always roll your own type to store in the Map (or List if you still need duplicate keys):
class WordDescription {
final String wordType;
final String definition;
WordDescription(String wordType, String definition) {
this.wordType = wordType;
definition = definition;
}
String getWordType() {
return wordType;
}
String getDefinition() {
return definition;
}
}
And use that in a List<Map.Entry<String, WordDescription>>. You can make wordType an enum if there's a pre-defined set of them (adjective, noun, etc.).
Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", (String) row[0]);
jsonObject.put("Client_Code", (String)row[1]);
jsonObject.put("Client_Description", (String)row[2]);
returnValues.add(jsonObject);
}
The first column of my table contains an integer value. I'm getting this error message:
Exception===java.lang.ClassCastException: cannot be cast to [Ljava.lang.Object;
Your itetator returns a string. You can't cast it to an array of object.
There is a split method in string, it splits your string by given regex and returns a String[] containing the split parts.
Since you provided no more information on that, I'm going to assume that the data in your row is separated by spaces.
String row = ll.next() // I assume row = "1234 5678 Description_No_Spaces"
String[] data = row.split("\\s+");
String record_Id = data[0];
You don't need an iterator, you can loop through results with foreach loop.
List <String> results =query.list();
for(String result: results) {
String[] row = /* user result.split(...) to get attributes*/
System.out.println("ReturnValues=========="+results);
Map<String, String> JSonObject=new HashMap<String, String>();
JSonObject.put("Record_Id", row[0]);
JSonObject.put("Client_Code", row[1]);
JSonObject.put("Client_Description",row[2]);
ReturnValues.add(JSonObject);
}
Check out String.split(String regex) docs.
Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())`enter code here`
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", String.valueOf(row[0]));
jsonObject.put("Client_Code", row[1]);
jsonObject.put("Client_Description", row[2]);
returnValues.add(jsonObject);
}
Hope this solves your problem
This is my xml format:
<taxmann>
<docdetails>
<info id="104010000000006516" date="20120120">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">\CIRCULARS\DIRECTTAXLAWS\HTMLFILES\CIRDGBACDD4836150012011122012012.htm</filepath>
<summary></summary>
<description></description>
<heading>DGBA.CDD. NO.H- 4836 /15.02.001/2011-12 | Clarification on Regulation of Interest Rates for Small Savings Schemes</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328155728957</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
I'm able to retrieve data of heading but I want to print date and id too but I'm not able to do this. Please tell me how to implement it.
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
String Heading= parser.getValue(e, KEY_NAME).replace("|", "|\n").replace("|", "");
map.put(KEY_NAME,Heading);
// adding HashList to ArrayList
menuItems.add(map);
}
This is my code please tell me the logic how I can parse, so that I can get date and id too.
Are you sure this is the easiest way to read that xml file? It just looks a bit too complicated. Why don't you navigate manually through the tree structure?
I would say you would get it this way:
SAXBuilder builder = new SAXBuilder();
Document doc;
doc = builder.build(file);
//rootElement would be your "taxmann" element
Element rootElement = doc.getRootElement();
Element docdetailsElement = rootElement.getChild("docdetails");
Element infoElement = docdetailsElement.getChild("info");
String id = infoElement.getAttributeValue("id");
String date = infoElement.getAttributeValue("date");
You should use Element#getAttribute(String name) method. In your case something like:
String id=e.getAttribute("id");
String date=e.getAttribute("date");