How to retrieve element value of XML using Java?
If your XML is a String, Then you can do the following:
String xml = ""; //Populated XML String....
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();
If your XML is in a file, then Document document
will be instantiated like this:
Document document = builder.parse(new File("file.xml"));
The document.getDocumentElement()
returns you the node that is the document element of the document (in your case <config>
).
Once you have a rootElement
, you can access the element's attribute (by calling rootElement.getAttribute()
method), etc. For more methods on java's org.w3c.dom.Element
More info on java DocumentBuilder & DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.
- Related question.
Update Here's an example to get "value" of element <requestqueue>
protected String getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
You can effectively call it as,
String requestQueueName = getString("requestqueue", element);
how to get the value from XML tag?
If you use .Net >= 3.5, you can use Linq to SQL to retrieve the values, here is an example:
XElement elem = XElement.Parse("<xml><LOCATION><P>Value1</P></LOCATION><ACCEPTED_VARIANTES VALUE=\"Value2\"/><PERIOD_DAY>Value3</PERIOD_DAY><AWARD_CRITERIA_DETAIL><Value4/></AWARD_CRITERIA_DETAIL></xml>");
var Value1 = elem.Element("LOCATION").Value;
var Value2 = elem.Element("ACCEPTED_VARIANTES").Attribute("VALUE").Value;
var Value3 = elem.Element("PERIOD_DAY").Value;
var Value4 = elem.Element("AWARD_CRITERIA_DETAIL").Element("Value4").Value;
Note: I added <xml>...</xml>
tags around the xml string to have it correctly parsing (only 1 root element is always accepted in XML. I assume your DB value is correctly formatted.
On a side note, this code is not protected, it means that if a tag you are looking for (like <LOCATION>
for instance) is not present, you'll get an exception (NullReferenceException
) when trying to access the Value
field.
Instead, you can try this:
var val1 = elem.Element("LOCATION");
var Value1 = val1 != null ? val1.Value : "no data found";
Which will avoid this exception when the tag is not present.
C# - Get value of xml element with its attribute
The Elements
query only finds immediate children of the current node. i.e. Elements
will only return the root list
element.
This either means you need to query like:
doc.Elements("list").Elements("resources").Elements(...
Or you can use Descendants
, which will many any descendant of the current node, so:
var name = (string)doc.Descendants("field")
.First(x => (string)x.Attribute("name") == "name");
How to get the value of an attribute from XML file in PHP?
You should be able to get this using SimpleXMLElement::attributes()
Try this:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
That will show you all the name/value attributes for the first foo
element. It's an associative array, so you can do this as well:
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
Best/Fastest way to find values of a element in a xml file
As @Sinatr mentions. Profiling should always be the first step when investigating performance.
A reasonable guess about what takes time would be
- IO
- Parsing
IO could be improved by getting a faster disk, or caching results in RAM. The later may greatly improve performance if multiple searches are done, but introduces issues like cache-invalidation.
According to "What is the best way to parse (big) XML in C# Code" XmlReader is the fastest way to parse xml. This blog suggest XmlReader is about 2.5 times faster.
If you have multiple files you could also try to process multiple files in parallel. Keep in mind IO is mostly serial, so you might not gain anything unless you have a SSD that can deliver data faster than files can be processed.
C# GET XML TAG VALUE
try out
linq to xml way
IEnumerable<XElement> direclty = infodoc.Elements("Settings").Elements("directory");
var rosterUserIds = direclty .Select(r => r.Attribute("value").Value);
OR
XmlNodeList nodeList=
(infodoc.SelectNodes("configuration/Settings/directory"));
foreach (XmlNode elem in nodeList)
{
string strValue = elem.Attributes[1].Value;
}
How to get attribute value and element value from XML with xmllint
Another option would be to use xmlstarlet to match the model
elements and then use concat() to output the desired values...
xmlstarlet sel -t -m "//_:model" -v "concat(@mh,' ',_:attribute)" -n devices.xml
outputs...
0x1058905 prod-vpn-gw-v01.e-x.com
0x1058907 prod-storage-san-z01-ssh.e-x.com
0x1058900 test-vpn-gw-v01
Note: I'm using version 1.6.1 of xmlstarlet. Not all versions support "_" for a namespace prefix. (Supported in versions 1.5.0+)
See http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139652416 for more info on the "sel" command of xmlstarlet.
Related Topics
Yii2 Global Filter/Behavior to Force User to Authenticate First
How to Receive a File via Http Put with PHP
Importing Multiple CSV Files to MySQL Tables
PHP How to Go One Level Up on Dirname(_File_)
How to Create a Random Hash/String
Read in Text File Line by Line PHP - Newline Not Being Detected
Avoiding Recursion with Doctrine Entities and Jmsserializer
Sort Array by Object Property in PHP
Sending Sms with Amazon Aws Services PHP
Why Are Certain Types of Prepared Queries Using Pdo in PHP with MySQL Slow
JSON_Encode Produce JSON_Error_Utf8 from Mssql-Select
Php, Failed Connecting to Database
How to Set an Absolute Include Path in PHP
Google-Like Search Engine in PHP/Mysql
Should I Mix Angularjs with a PHP Framework