How to get key-value of XML in hashmap using java - java

I am facing a issue where I am not able to get the value in my hashmap as per the key of the XML while I am getting the parent key
Code I am using:
public static void main(String[] args) throws IOException {
try {
String XML="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<sj0:Msg>\r\n" +
" xmlns:sj0=\"http://fakesite.org/\"\r\n" +
" xmlns:sj1=\"http://fakesite.org/ind\"\r\n" +
" <sj0:Hdr>\r\n" +
" <sj2:Option>CreateTxn</sj2:Option>\r\n" +
" <sj2:ID>172246</sj2:ID>\r\n" +
" <sj2:CountryCode>CR</sj2:CountryCode>\r\n" +
" </sj0:Hdr>\r\n" +
" <sj0:ReqDet>\r\n" +
" <sj0:MReq>\r\n" +
" <sj0:qCore>\r\n" +
" <sj1:Reference>12345678</sj1:Reference>\r\n" +
" <sj1:BrnCode>CLM</sj1:BrnCode>\r\n" +
" <sj1:Source>M1T722</sj1:Source>\r\n" +
" <sj1:TxnLegCount>2</sj1:TxnLegCount>\r\n" +
" </sj0:qCore>\r\n" +
" </sj0:MReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Amt>19.28</sj1:Amt>\r\n" +
" <sj1:Dt>2019-09-04</sj1:Dt>\r\n" +
" <sj1:Date>2019-06-27</sj1:Date>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Ind>DC</sj1:Ind>\r\n" +
" <sj1:Currency>US</sj1:Currency>\r\n" +
" <sj1:LAmt>20.28</sj1:LAmt>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" </sj0:ReqDet>\r\n" +
"</sj0:Msg>";
String XString = XML;
System.out.println(XML);
HashMap<String, String> values = new HashMap<String, String>();
Document xml = convertStringToDocument(XString);
Node user = xml.getFirstChild();
NodeList childs = user.getChildNodes();
Node child;
for (int i = 0; i < childs.getLength(); i++) {
child = childs.item(i);
System.out.println(child.getNodeName());
System.out.println(child.getNodeType());
System.out.println(child.getUserData("Source"));
System.out.println(child.getTextContent());
values.put(child.getNodeName(), child.getTextContent());
}
System.out.println("Source name");
System.out.println(values.toString());
System.out.println(values.get("Source"));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Output:
{sj0:ReqDet=
12345678
CLM
M1T722
2
19.28
2019-09-04
2019-06-27
DC
US
20.28
, #text= , sj0:Hdr= CreateTxn 172246 CR }
I need to add Source in haspmap key not ReqDet.
I am facing issue to traverse through the XML.
Any idea where I am going wrong and also please explain how I can get the value of other keys-value i.e. Ind key of RCore parent key.
I am fine with any other approach or library to do achieve this task if this library have issue

below line of code having "*" which means it will select all nodes/key-values from the XML
NodeList nodeList = doc.getElementsByTagName("*");
Below is the full code works for me:
public static void main(String[] args) throws IOException {
String XML="YOUR XML";
HashMap<String, String> values =convertStringToDocument(XML);
System.out.println("values = "+values.get("sj1:Source"));
}
public static HashMap<String, String> convertStringToDocument(String xmlStr) {
HashMap<String, String> values = new HashMap<String, String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
EntityResolver resolver = new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
String empty = "";
ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
System.out.println("resolveEntity:" + publicId + "|" + systemId);
return new InputSource(bais);
}
};
builder.setEntityResolver(resolver);
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
values.put(node.getNodeName(), node.getTextContent());
}
}
return values;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

How to parse soap string in java

I have written the below code to parse a string in java but its not printing out a blank message.
How can I get specific parts from a SOAP message and get their values?
I want to get the error and the message in the request.
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>"
+ "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>"
+ "<totalFailed>0</totalFailed>"
+ "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>"
+ "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>"
+ "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>"
+ "<closingBalance>0.0</closingBalance>"
+ "</response>"
+ "</ns2:processResponse>"
+ "</S:Body>"
+ "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element meta = null;
Element error = null;
Element status_message = null;
String status_code= "";
String message = "";
try
{
doc = builder.build(in);
root = doc.getRootElement();
meta = root.getChild("processResponse").getChild("response");
error = meta.getChild("error");
status_message = meta.getChild("message");
status_code = error.getText();
message = status_message.getText();
}catch (Exception e)
{
// do what you want
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
The response being generated is
status_code:
message:
You are making some mistakes in your code while picking up elements in xml. You can use this code and check,
public static void main(String[] args) {
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>" + "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>" + "<totalFailed>0</totalFailed>" + "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>" + "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>" + "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>" + "<closingBalance>0.0</closingBalance>" + "</response>"
+ "</ns2:processResponse>" + "</S:Body>" + "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element error = null;
Element status_message = null;
String status_code = "";
String message = "";
try {
doc = builder.build(in);
root = doc.getRootElement();
Element body = root.getChild("Body", Namespace.getNamespace("S", "http://schemas.xmlsoap.org/soap/envelope/"));
Element processResponse = body.getChild("processResponse", Namespace.getNamespace("ns2", "http://ws.xxxxx.com/"));
Element response = processResponse.getChild("response");
error = response.getChild("error");
status_message = response.getChild("message");
status_code = error.getText();
message = status_message.getText();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
}
For me this is giving following output,
status_code: 1
message: Invalid

parsing Xml with NodeList and DocumentBuilder and getting values

I've followed almost all of the SO questions and answers, some make sense while others don't, i'm able to get some of my xml working some of the time. At this point I have a hobbled gob of nothing.
Below is my xml that i am trying work with
<GET_GUESS_CHART>
<sort_by_letter>
<letter_row>
<letter>A</letter>
<guess>16</guess>
<rank>3</rank>
</letter_row>
<letter_row>
<letter>B</letter>
<guess>5</guess>
<rank>1</rank>
</letter_row>
</sort_by_letter>
<sort_by_rank>
<letter_row>
<letter>A</letter>
<guess>16</guess>
<rank>1</rank>
</letter_row>
<letter_row>
<letter>E</letter>
<guess>15</guess>
<rank>2</rank>
</letter_row>
</sort_by_rank>
</GET_GUESS_CHART>
I want to loop through the document and loop through 'sort_by_letters' and 'sort_by_rank' and get values for each 'letter_row'.
Here is how i get the document:
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Download the XML file
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
I'm able to actually get the document, but for the life of me can not figure how to work it to get what i need.
All you need to do is to walk the DOM tree...
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXML {
private static final String XML = "<?xml version=\"1.0\"?>\n"
+ "<GET_GUESS_CHART>"
+ " <sort_by_letter>"
+ " <letter_row>"
+ " <letter>A</letter>"
+ " <guess>16</guess>"
+ " <rank>3</rank>"
+ " </letter_row>"
+ " <letter_row>" +
+ " <letter>B</letter>"
+ " <guess>5</guess>"
+ " <rank>1</rank>"
+ " </letter_row>"
+ " </sort_by_letter>"
+ " <sort_by_rank>"
+ " <letter_row>"
+ " <letter>A</letter>"
+ " <guess>16</guess>"
+ " <rank>1</rank>"
+ " </letter_row>"
+ " <letter_row>"
+ " <letter>E</letter>"
+ " <guess>15</guess>"
+ " <rank>2</rank>"
+ " </letter_row>"
+ " </sort_by_rank>"
+ "</GET_GUESS_CHART>";
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(XML.getBytes()));
NodeList rootElement = doc.getChildNodes();
NodeList sortByNodes = rootElement.item(0).getChildNodes();
for (int k = 0; k < sortByNodes.getLength(); k++) {
Node sortBy = sortByNodes.item(k);
System.out.println("SORT BY: " + sortBy.getNodeName());
NodeList letterRows = sortBy.getChildNodes();
for (int j = 0; j < letterRows.getLength(); j++) {
Node letterRow = letterRows.item(j);
NodeList letterRowDetails = letterRow.getChildNodes();
if (letterRowDetails.getLength() > 0) {
String letter = null;
String guess = null;
String rank = null;
for (int i = 0; i < letterRowDetails.getLength(); i++) {
Node detail = letterRowDetails.item(i);
if (detail.getNodeName().equals("letter")) {
letter = detail.getTextContent();
} else if (detail.getNodeName().equals("guess")) {
guess = detail.getTextContent();
} else if (detail.getNodeName().equals("rank")) {
rank = detail.getTextContent();
}
}
System.out.println("Letter=" + letter + ", guess=" + guess + ", rank=" + rank);
}
}
}
}
}
(You'll probably build an object and add it to some result list instead of the System.out line...)
OUTPUT:
SORT BY: #text
SORT BY: sort_by_letter
Letter=A, guess=16, rank=3
Letter=B, guess=5, rank=1
SORT BY: #text
SORT BY: sort_by_rank
Letter=A, guess=16, rank=1
Letter=E, guess=15, rank=2
To answer the comment: if you wanted to JUST get the "sort_by_letter" XML elements, you can add an extra if clause here...
...
for (int k = 0; k < sortByNodes.getLength(); k++) {
Node sortBy = sortByNodes.item(k);
if(sortBy.getNodeName().equals("sort_by_letter")) {
System.out.println("SORT BY: " + sortBy.getNodeName());
...

Java Convert InputStream of XML to Document object always results in NULL

I am trying to parse a XML string into org.w3c.dom.Document object.
I have looked at solutions provided here, here and a few other blogs that give a variation of the same solution. But the Document object's #Document variable is always null and nothing gets parsed.
Here is the XML file
XMLMappingValidator v = new XMLMappingValidator("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<mapping>\n" +
"<container>\n" +
"<source-container>c:\\stem.csv</source-container>\n" +
"<source-type>CSV_FILE</source-type>\n" +
"<target-container>db</target-container>\n" +
"<target-type>MySQL_TABLE</target-type>\n" +
"</container>\n" +
"<entity>\n" +
"<source-entity>stem</source-entity>\n" +
"<target-entity>tbl_stem</target-entity>\n" +
"</entity>\n" +
"<attributes>\n" +
"<attribute>\n" +
"<datatype>SMALLINT</datatype>\n" +
"<source-attribute>id</source-attribute>\n" +
"<target-attribute>id</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>VARCHAR</datatype>\n" +
"<source-attribute>name</source-attribute>\n" +
"<target-attribute>name</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>TEXT</datatype>\n" +
"<source-attribute>body</source-attribute>\n" +
"<target-attribute>body</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>DATETIME</datatype>\n" +
"<source-attribute>date</source-attribute>\n" +
"<target-attribute>date</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>VARCHAR</datatype>\n" +
"<source-attribute>info</source-attribute>\n" +
"<target-attribute>info</target-attribute>\n" +
"</attribute>\n" +
"</attributes>\n" +
"</mapping>");
The constructor XMLMappingValidator object's code is as follows
public class XMLMappingValidator {
private Document xml;
public XMLMappingValidator (String xmlString) throws
IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.xml =
builder.parse(new InputSource(new StringReader(xmlString)));
}
public Document getXML() {
return xml;
}
}
When I call v.getXML().toString() I get [#document: null]
Clearly, the parse is failing. But I don't understand why.
Any suggestions/help is greatly appreciated.

Using Crawler4j to print an Arraylist to HTML file?

Basics of this program;
Runs a webcrawler based on PerentUrl and Keyword specified by the user in Controller (main). If the Keyword is found in the page text, the Url is then saved to an array list;
ArrayList UrlHits = new ArrayList();
Once the crawl is complete the program will call methods from the WriteFile class in the main to write a html file containing all the UrlHits.
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
All but f.addUrl work correctly, creating a html file with the correct name and directory. But none of the strings from the ArrayList output to the file.
public static void main(String[] args) throws Exception {
RobotstxtConfig robotstxtConfig2 = new RobotstxtConfig();
String crawlStorageFolder = "/Users/Jake/Documents/sem 2/FYP/Crawler/TestData";
int numberOfCrawlers = 1;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setMaxDepthOfCrawling(21);
config.setMaxPagesToFetch(24);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
Scanner perentUrl = new Scanner(System.in);
System.out.println("Enter full perant Url... example. http://www.domain.co.uk/");
String Url = perentUrl.nextLine();
Scanner keyword = new Scanner(System.in);
System.out.println("Enter search term... example. Pies");
String Search = keyword.nextLine();
System.out.println("Searching domain :" + Url);
System.out.println("Keyword:" + Search);
ArrayList<String> DomainsToInv = new ArrayList<String>();
ArrayList<String> SearchTerms = new ArrayList<String>();
ArrayList<String> UrlHits = new ArrayList<String>();
DomainsToInv.add(Url);
SearchTerms.add(Search);
controller.addSeed(Url);
controller.setCustomData(DomainsToInv);
controller.setCustomData(SearchTerms);
controller.start(Crawler.class, numberOfCrawlers);
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
}
}
public class Crawler extends WebCrawler {
#Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
ArrayList<String> SearchTerms = (ArrayList<String>) this.getMyController().getCustomData();
ArrayList<String> UrlHits = (ArrayList<String>) this.getMyController().getCustomData();
for (String Keyword : SearchTerms) {
System.out.println("Searching Keyword: " + Keyword);
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
int KeywordCounter = 0;
String pagetext = htmlParseData.getText();
Pattern pattern = Pattern.compile(Keyword);
Matcher match1 = pattern.matcher(pagetext);
if (match1.find()) {
while (match1.find()) {
KeywordCounter++;
}
System.out.println("FOUND " + Keyword + " in page text. KeywordCount: " + KeywordCounter);
UrlHits.add(url);
for (int i = 0; i < UrlHits.size(); i++) {
System.out.print(UrlHits.get(i) + "\n");
System.out.println("=============");
}
} else {
System.out.println("Keyword search was unsuccesful");
System.out.println("=============");
}
}
}
}
public class WriteFile {
private Formatter x;
public void openfile(String keyword) {
try {
x = new Formatter(keyword + ".html");
} catch (Exception e) {
System.out.println("ERROR");
}
}
public void StartHtml() {
x.format("%s %n %s %n %s %n %s %n %s %n ", "<html>", "<head>", "</head>", "<body>", "<center>");
}
public void addUrl(ArrayList<String> UrlHits) {
for (String list : UrlHits) {
x.format("%s%s%s%s%s%n%s%n", "", list, "", "<br>");
}
}
public void EndHtml() {
x.format("%s %n %s %n %s %n", "</center>", "</body>", "</html>");
}
public void closeFile() {
x.close();
}
}
Apologies for the class headers outside the code blocks its a little fiddly. I have tried a few different "for" statements to get the method to output the array list but it doesn't seem to be having it. The strings are being added to the array list as i can call them using a for loop in the main. But when i pass the array list to the method addUrl, it comes up with squat. is there an easier way to use arraylists using formatters and .format?
Thanks for you help

reading from XMl file in java

I have a simple XML file
<requirements>
<requirement>
<name> SwitchON</name>
<id>1</id>
<text>The Light shall turn on when the Switch is on.</text>
</requirement>
<requirement>
<name>SwitchOFF</name>
<id>2</id>
<text>The Light shall turn off when the Switch is off.</text>
</requirement>
<requirement>
<name>Lightbulb</name>
<id>3</id>
<text>The Light bulb shall be connected </text>
</requirement>
<requirement>
<name>Power</name>
<id>4</id>
<text>The Light shall have the power supply</text>
</requirement>
</requirements>
I am trying to show the information in this file in a table model.
I have a method (readFromXMl) that reads the XML file and returns a table model.
public static RequirementTable readFromXMl(String fileName) {
RequirementTable T = new RequirementTable();
Requirement R = new Requirement();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
doc.getDocumentElement().normalize();
NodeList listOfRequirements = doc.getElementsByTagName("requirement");
int test = listOfRequirements.getLength();
System.out.println("Total no of people : " + test);
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
if (RequirementNode.getNodeType() == Node.ELEMENT_NODE) {
Element RequirementElement = (Element) RequirementNode;
NodeList IdList = RequirementElement.getElementsByTagName("id");
Element IdElement = (Element) IdList.item(0);
NodeList textIdList = IdElement.getChildNodes();
R.setId(Integer.parseInt(textIdList.item(0).getNodeValue()));
NodeList DescriptionList = RequirementElement.getElementsByTagName("text");
Element DescriptionElement = (Element) DescriptionList.item(0);
NodeList textDescriptionList = DescriptionElement.getChildNodes();
R.setText(textDescriptionList.item(0).toString());
NodeList NameList = RequirementElement.getElementsByTagName("name");
Element NameElement = (Element) NameList;
NodeList textNameList = NameElement.getChildNodes();
if (textNameList.item(0).toString().equals("SwitchON")) {
T.addRequirement((SwitchOnReq)R);
} else if (textNameList.item(0).toString().equals("SwitchOFF")) {
T.addRequirement((SwitchOFFReq)R);
} else if (textNameList.item(0).toString().equals("LightBulb")) {
T.addRequirement((BulbRequirement)R);
} else if (textNameList.item(0).toString().equals("Power")) {
T.addRequirement((PowerRequirement)R);
}
}
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
return T;
}
However in this line I am getting an error which says the the pointer is null
Element IdElement = (Element) IdList.item(0); IdElement is null!!
Instead of all the looping and other xml ugliness, let me suggest a little helper method:
private static String getNodeValue(Node n, String path)
throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
return (String) xpath.evaluate(path, n, XPathConstants.STRING);
}
Use like this:
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
System.out.println("name:" + getNodeValue(RequirementNode, "name"));
System.out.println("id:" + getNodeValue(RequirementNode, "id"));
System.out.println("text:" + getNodeValue(RequirementNode, "text"));
...
to get all the values and set your requirements.

Categories