Как получить значение элемента XML с помощью Java?
Если ваш XML является строкой, то вы можете сделать следующее:
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();
Если ваш XML находится в файле, то Document document будет создан таким образом:
Document document = builder.parse(new File("file.xml"));
document.getDocumentElement() возвращает node, который является элементом документа документа (в вашем случае ).
Как только у вас есть rootElement , вы можете получить доступ к атрибуту элемента (путем вызова метода rootElement.getAttribute() ) и т.д. Для получения дополнительных методов в java org. w3c.dom.Element
Дополнительная информация о java DocumentBuilder и DocumentBuilderFactory. Помните, предоставленный пример создает дерево DOM XML, поэтому, если у вас есть огромные данные XML, дерево может быть огромным.
Обновить. Здесь приведен пример получения «значения» элемента
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; >
Вы можете эффективно называть его как
String requestQueueName = getString("requestqueue", element);
Как получить элемент в Set?
если в Set хранится строка «Tim», и ты хочешь получить строку «Tim» — какой смысл в Set? даже если бы была возможность сделать set.get(«Tim») ?
а если не я создаю set мне просто его нужно использовать, достать значение — так что поможет только конвертировать его в List или другую коллекцию ?
@mtb, если я правильно понял вы хотите проверить наличие элемента в коллекции (если это так измените вопрос), для этого можно воспользоваться методом contains.
«а если элементном в Set является объект» ну тогда нужно указать объект в вопросе и по какому полю объекта вы будете находить нужный.
3 ответа 3
hset.stream().filter(data -> Objects.equals(data, "Tim")).findFirst().get()
Тоже столкнулся с этим вопросом. Я так понял, что до появления Stream API можно было написать метод для поиска этого эемента, который использовал бы итератор.
@Олексій Моренець, зачем? Куда проще -> делаем перебор элементов коллекции циклом -> в цикле выставляем условие на соответствие искомогу элемента -> return element;
cats.removeIf(elem -> elem.name.equals("Васька"));
Удаляет объект Cat с полем name == «Васька» из Set cats
Думаю, это примерно то что было нужно автору вопроса. Я написал такое:
а IDEA предложила сократить. Вообще полезно смотреть что она предлагает 🙂
В HashSet — нельзя получить элемент по ключу.
HashSet инкапсулирует HashMap. Вы лишь можете проверить наличие элемента в коллекции.
Если же все таки вам нужно получить элемент, тогда вы должны вызывать iterator() или используйте for() (под капотом он использует Iterator). Если сразу вы решили, что вам нужно будет получать данные по ключу, то HashSet не подойдет вам как структура для хранения ваших элементов, во первых она не предназначена для этого, а во вторых сложность времени поиска элемента занимает O(n).
Как получить значение из элементов коллекции List
Исходные данные-результат запроса из базы данных в виде List
for (Records a : records) < for (int i = 0; irow ++; >
1 ответ 1
Сделайте метод, который будет возвращать список Ваших полей. Например:
class TestRecord < int field1; int field2; int filed3; ListgetFields() < return Arrays.asList(field1, field2, filed3); >>
excelTargets.add(new ExcelTarget(sheetName, row, columns[i], a.getFields().get(i)));
Если Ваш класс Records нельзя отредактировать, можно расширить его функциональность с помощью наследования либо композиции. Наследование:
class TestRecord < private int field1; private int field2; private int filed3; public int getField1() < return field1; >public int getField2() < return field2; >public int getFiled3() < return filed3; >> class MyTestRecord extends TestRecord < ListgetFields() < return Arrays.asList(getField1(), getField2(), getFiled3()); >>
TestRecord record = new TestRecord(); List fields = Arrays.asList(record.getField1(), record.getField2(), record.getFiled3()); excelTargets.add(new ExcelTarget(sheetName, row, columns[i], fields.get(i)));
Если все таки ни один из предложенных вариантов не подходит, можно использовать java reflection.
class TestRecord < private int field1 = 1; private int field2 = 2; private int filed3 = 3; >TestRecord record = new TestRecord(); List values = new ArrayList<>(); Field[] fields = TestRecord.class.getDeclaredFields(); for (Field field : fields)
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 ).
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.
Update Here’s an example to get «value» of element
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);
Fair enough, if someone is still on JDK 1.4 then your approach is reasonable. If they are on 1.5 or later then the javax.xml.xpath library is much easier. I hate to see people doing things the hard way when a better way exists.
@Blaise Doughan, you will be surprised at how many companies (most especially banks) still run JDK 1.4.
Agreed there are developers using JDK 1.4, and that your solution is appropriate to JDK 1.4. If, however they are using JDK 1.5 or above the javax.xml.xpath library is more appropriate. There are many developers with JDK 1.5 and 1.6 as baselines.
In case you just need one (first) value to retrieve from xml:
public static String getTagValue(String xml, String tagName)< return xml.split("")[1].split(""+tagName+">")[0]; >
In case you want to parse whole xml document use JSoup:
Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); for (Element e : doc.select("Request"))
@Klesun Saying that it will behave incorrectly a bit bold IMHO. It will return the content of the tag regardless of what is inside the tag. What do you expect it to do?
If you are just looking to get a single value from the XML you may want to use Java’s XPath library. For an example see my answer to a previous question:
It would look something like:
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Demo < public static void main(String[] args) < DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try < DocumentBuilder builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse("E:/test.xml"); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE); System.out.println(node.getNodeValue()); >catch (Exception e) < e.printStackTrace(); >> >
Required Node found NodeList on Node node = (NodeList) xPath.evaluate(«/Request/@name», dDoc, XPathConstants.NODE);
There are a number of different ways to do this. You might want to check out XStream or JAXB. There are tutorials and the examples.
@sam: And you probably want to check this SO question as well, stackoverflow.com/questions/1558087/xstream-or-simple.
If the XML is well formed then you can convert it to Document. By using the XPath you can get the XML Elements.
Form XML-String Create Document and find the elements using its XML-Path.
Document doc = getDocument(xml, true); public static Document getDocument(String xmlData, boolean isXMLData) throws Exception < DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); dbFactory.setIgnoringComments(true); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc; if (isXMLData) < InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData)); doc = dBuilder.parse(ips); >else < doc = dBuilder.parse( new File(xmlData) ); >return doc; >
Use org.apache.xpath.XPathAPI to get Node or NodeList.
System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()")); NodeList nodeList = getNodeList(doc, "/stackusers"); System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList)); System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0))); public static String getNodeValue(Document doc, String xpathExpression) throws Exception < Node node = org.apache.xpath.XPathAPI.selectSingleNode(doc, xpathExpression); String nodeValue = node.getNodeValue(); return nodeValue; >public static NodeList getNodeList(Document doc, String xpathExpression) throws Exception
System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age")); static XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath(); public static String getXPathFactoryValue(Document doc, String xpathExpression) throws XPathExpressionException, TransformerException, IOException
System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age")); public static String getDocumentElementText(Document doc, String elementName)
Get value in between two strings.
String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "", " "); System.out.println("StringUtils.substringBetween():"+nodeVlaue);
public static void main(String[] args) throws Exception < String xml = "Yash 30 "; Document doc = getDocument(xml, true); String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "", " "); System.out.println("StringUtils.substringBetween():"+nodeVlaue); System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age")); System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age")); System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()")); NodeList nodeList = getNodeList(doc, "/stackusers"); System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList)); System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0))); > public static String getXmlContentAsString(Node node) throws TransformerException, IOException < StringBuilder stringBuilder = new StringBuilder(); NodeList childNodes = node.getChildNodes(); int length = childNodes.getLength(); for (int i = 0; i < length; i++) < stringBuilder.append( toString(childNodes.item(i), true) ); >return stringBuilder.toString(); >
StringUtils.substringBetween():30 DocumentElementText:30 javax.xml.xpath.XPathFactory:30 XPathAPI:30 XPathAPI NodeList: Yash 30 XPathAPI NodeList:Yash 30