XML node list as JavaFX observable list? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
got a problem...
I have some XML file with root element, 3 element with same name and different attribute and also each element has got some elements.
I want to have element attributes called "id" in FX observable list.
No idea what to do.

Since you didn´t give me much information, I have to explain it with some dummy-code.
So let´s say you have this XML:
<root id="0">
<sub1 id="1">
<hell1>hell1</hell1>
</sub1>
<sub2>
<hell2 id="2">hell2</hell2>
</sub2>
<sub3>sub3</sub3>
</root>
Please note, that the "id"-attributes are in different element levels, as you said.
From here I would also advise you to use xpath like Heri.
The simplest xpath to get all elements with "id"-attributes from XML is:
//*[#id]
If you don´t know how to work with XML and Xpath in Java you can look it up here:
How to read XML using XPath in Java
Which is the best library for XML parsing in java
If i wanted to get all "id"-attribute values from my XML it would look like this:
// My Test-XML
final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<root id=\"0\">\n" +
"\t<sub1 id=\"1\">\n" +
"\t\t<hell1>hell1</hell1>\n" +
"\t</sub1>\n" +
"\t<sub2>\n" +
"\t\t<hell2 id=\"2\">hell2</hell2>\n" +
"\t</sub2>\n" +
"\t<sub3>sub3</sub3>\n" +
"</root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Here you have to put your XML-Source (String, InputStream, File)
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
// The xpath from above
XPathExpression expr = xpath.compile("//*[#id]");
// Here you get the node-list of all elements with an attribute named "id"
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// run through all nodes
Node node = nodeList.item(i);
// fetch the values from the "id"-attribute
final String idValue = node.getAttributes().getNamedItem("id").getNodeValue();
// Do something awesome!!!
System.out.println(idValue);
}
I assume that you know how to put the values into your observable list then. :)
If you have any more questions, feel free to ask.
PS: If you show me your XML, I can help you in a more efficient way.

Related

how to extract specific word from given string? I want Only MyName from the given string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
String s= "<tr><td><b>ErrorCode</b></td><td>myName</td></tr><tr><td><b>";
String p[]= s.split(`enter code here`);
As per your string it looks like HTML and if you want to parse it, there are multiple ways to do it. As in comments one of the ways suggested is JSOUP.
If you are aware of the tags and path you can use XPath to obtain the information you need.
For reference example as below:
String s = "<tr><td><b>ErrorCode</b></td><td>myName</td></tr>";
InputSource inputXML = new InputSource(new StringReader(s));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String xpathExpression = "/tr/td[2]"; //Xpath to evaluate and find your value as per your String.
XPathExpression expr = xpath.compile(xpathExpression);
//It will give you List of Nodes in which you can iterate and find out your value.
NodeList nodes = (NodeList) expr.evaluate(inputXML, XPathConstants.NODESET);
System.out.println(nodes.item(0).getTextContent());
Another approach is to use Html Parsing Libraries as given in suggestions.
JSoup
For Jsoup (XML) below is reference code can be used.
String s = "<tr><td><b>ErrorCode</b></td><td>myName</td></tr>";
Document doc = Jsoup.parse(s,"", Parser.xmlParser());
Elements td = doc.select("td");
System.out.println(td.get(1).text());
For Jsoup(Html) your tags need to be proper.
String s = "<table><tr><td><b>ErrorCode</b></td><td>myName</td></tr></table>";
Document doc = Jsoup.parse(s);
Elements td = doc.select("td");
System.out.println(td.get(1).text());

Java XPath scan file looking for a word

Im building an application that will taka a word from user and then scan file using XPath returning true or false depending on wheather the word was found in that file or not.
I have build following class that implements XPath, but i am either missunderstanding how it should work or there is something wrong with my code. Can anyone explain to me how to use Xpath to make full file search?
public XPath() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
FileInputStream fileIS = new FileInputStream("text.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(fileIS);
XPathFactory xPathfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xPath = xPathfactory.newXPath();
XPathExpression expr = xPath.compile("//text()[contains(.,'java')]");
System.out.println(expr.evaluate(xmlDocument, XPathConstants.NODESET));
}
And the xml file i am currently testing on.
<?xml version="1.0"?>
<Tutorials>
<Tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
</Tutorials>
Found the solution, i was missing correct display of the found entries and as someone pointed out in comment 'java' is in arguments and i want to scan only text fields so it would be never found, after adding following code and changing the word my app will look for, application works
Object result = expr.evaluate(xmlDocument, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Your XPath is searching the text() nodes, but the word java appears in the #type attribute (which is not a text() node).
If you want to search for the word in both text() and #* then you could use a union | operator and check for either/both containing that word:
//text()[contains(. ,'java')] | //#*[contains(., 'java')]
But you might also want to scan comment() and processing-instruction(), so could generically match on node() and then in the predicate test:
//node()[contains(. ,'java')] | //#*[contains(., 'java')]
With XPath 2.0 or greater, you could use:
//node()[(.|#*)[contains(., 'java')]]

XML Parse - Issue with parsing text from specific Node [duplicate]

This question already has answers here:
Getting an attribute value in xml element
(3 answers)
Closed 5 years ago.
Face an issue in parsing XML to extract data from a specific node. I referred to Link1 Link2 Link3. Please note, am able to parse & get the data for other nodes in the below xml file like id, order_id etc. But for the below line / node, unable to extract the info of segment_id & instrument_id:
<trade segment_id="NSE-F&O " instrument_id="NSE:INFRATEL17NOVFUT">
Not sure if the way the XML file is setup or the way I am trying to extract the data for that specific node is wrong. Hope the specific issue I face is clear.
XML File:
<contract_note version="0.1">
<contracts>
<contract>
<id>CNT-17/18-5310750</id>
<name>CONTRACT NOTE CUM BILL</name>
<description>None</description>
<timestamp>2017-11-01</timestamp>
<trades>
<trade segment_id="NSE-F&O " instrument_id="NSE:INFRATEL17NOVFUT">
<id>37513030</id>
<order_id>1300000000352370</order_id>
<timestamp>09:20:48</timestamp>
<description>None</description>
<type>buy</type>
<quantity>1700</quantity>
<average_price>444.2</average_price>
<value>755140.0</value>
</trade>
</trades>
</contract>
</contracts>
</contract_note>
Code:
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
NodeList cNoteList = doc.getElementsByTagName("contract");
Node nNode = cNoteList.item(0);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
for (int j = 1; j <= eElement.getElementsByTagName("trade").getLength(); j++) {
// Check if data can be read for Node - 'id'
System.out.println(eElement.getElementsByTagName("id").item(j).getTextContent();
// Check if data can be read for segment_id & instrument_id
System.out.println("Scrip: " + eElement.getElementsByTagName("trade").item(0).getTextContent());
}
}catch (Exception e) {
e.printStackTrace();
}
Edit:
Corrected the xml file info provided above.
As #Juan commented, your XML is bad. Fix it by following the required XML escaping rules and replacing segment_id="NSE-F&O " with segment_id="NSE-F&O ".
If you cannot change the XML, then see How to parse invalid (bad / not well-formed) XML? for options, but the best option is to fix the XML at the source.

How to get XML content as a String

<root>
<h id="1">
<d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d>
<d value="6"><open>10:00</open><close>2:00</close></d>
<d value="7"><open>10:00</open><close>21:00</close></d>
</h>
<h id="2">
</h>
</root>
Here I have the XML which root has list of <h> tagged nodes. Now I need to break these into parts and set it into different variables (add into a map).
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(data.getBytes("utf-8"))));
NodeList nList = doc.getElementsByTagName("h");
for (int i = 0; i < nList.getLength(); i++)
{
Node nNode = nList.item(i);
System.out.println(nNode.getAttributes().getNamedItem("id") + " " + ?????);
}
what should I call in order to get the value (String value) of a nNode ?
Here is what Im looking for as the asnwer for the above code once some one fills the ????
1 <h id="1"><d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d><d value="6">open>10:00</open><close>2:00</close></d><d value="7"><open>10:00</open><close>21:00</close></d></h>
2 <h id="2"></h>
And i don't mind having as root element
You can use Node.getTextContent() to conveniently get all the text of a node (gets text of children as well).
See Parsing xml file contents without knowing xml file structure for a short example.
If you're trying to get the value attributes of the d nodes (I can't actually tell, your question is slightly unclear to me), then it would be different -- for that you would iterate through the children of each h node (use getChildNodes() or getFirstChild() + getNextSibling()) then grab their value attributes just as you are getting the id attribute of the h nodes (the above link also shows an example of iterating through child nodes).
Have you tried jDom library? http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html
XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(your_jdom_element);
Have you tried nNode.toString() if you are using Node from javax.xml.soap.Node.
You can use that:
http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getTextContent()
but your sample nNode has other nodes, not just text. It seems you need helper method to construct String from child nodes.
Pass your nNode to nodeToString
XML Node to String in Java

How do I get the tag 'Name' from a XML Node in Java (Android)

I have a tiny little problem parsing an XML file in Java (Android).
I have an XML file that is like this:
<Events>
<Event Name="Olympus Has Fallen">
...
</Event>
<Event Name="Iron Man 3">
...
</Event>
</Events>
I already managed to get the NodeList by doing this:
URL url = new URL("********");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Event");
Also I managed to get every single item of the NodeList by doing this:
for (int i = 0; i < nodeList.getLength(); i++) {
// Item
Node node = nodeList.item(i);
Log.i("film", node.getNodeName());
}
But this just Logs: "Event" instead of the value of the Name tag.
How do I output the value of this 'name' tag from the XML.
Can anyone help me with this one?
Thanks in advance!
But this just Logs: "Event" instead of the value of the Name tag.
Yes, because you're asking for the name of the element. There isn't a Name "tag" - there's a Name attribute, and that's what you should find:
// Only check in elements, and only those which actually have attributes.
if (node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
Node nameAttribute = attributes.getNamedItem("Name");
if (nameAttribute != null) {
System.out.println("Name attribute: " + nameAttribute.getTextContent());
}
}
(It's very important to be precise in terminology - it's worth knowing the difference between nodes, elements, attributes etc. It will help you enormously both when communicating with others and when looking for the right bits of API to call.)

Categories