java 获取xml元素节点的文本内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4148238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting text content of element node of xml
提问by yogsma
I am trying to get the text content of first node in this XML. First node (Deductible) is an element node, when I get the text content, I get "Calendar Year$1,500$1,500$3,000"instead of just "Calendar Year"
我正在尝试获取此 XML 中第一个节点的文本内容。第一个节点(Deductible)是一个元素节点,当我得到文本内容时,我得到“日历年$1,500$1,500$3,000”而不是“日历年”
<Item type="Deductible" name="Deductible" id="a">Calendar Year
<Item type="Text" name="Individual" id="b">,500</Item>
<Item type="Text" name="Individual Out-of-network" id="id_4">,500</Item>
<Item type="Text" name="Family" id="c">,000</Item>
<Item type="Text" name="Family Out-of-network:" id="id_5">,000</Item>
</Item>
This is what I am trying
这就是我正在尝试的
dbuilder = dbc.newDocumentBuilder();
Document doc = dbuilder.parse(new InputSource(new StringReader(plan.getProvisions())));
NodeList nl = doc.getElementsByTagName("Item");
for(int i = 0 ; i < nl.getLength(); i++){
if(i == row){
org.w3c.dom.Element e = (org.w3c.dom.Element)nl.item(i);
value = e.getTextContent();
}
}
回答by khachik
If the root tag is <Item type="Deductible" ...
you can do doc.getDocumentElement().getChildNodes().item(0).getNodeValue();
如果根标签是<Item type="Deductible" ...
你可以做的 doc.getDocumentElement().getChildNodes().item(0).getNodeValue();
Otherwise you can check the type
attribute value to detect the Item
element in the nodelist got from getElementsByTagName("Item");
.
否则,您可以检查type
属性值以检测Item
从getElementsByTagName("Item");
.
I would use the Java(1.5) XPathAPI to select the Item/@type='Deductible'
elements.
我会使用Java(1.5) XPathAPI 来选择Item/@type='Deductible'
元素。