Java DOM xml 无法获取子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6444597/
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
Java DOM xml cant get child
提问by Raptrex
My XML looks like this:
我的 XML 看起来像这样:
<ConnProf ConnProfID="1111">
<ConnNum>1</ConnNum>
<IsMSPA>false</IsMSPA>
<IsArray>false</IsArray>
<IsDDOR>false</IsDDOR>
<Subsystem SSID="2222"ConnProfID="3333">
<SSName>AA</SSName>
<GenericSSName>AA</GenericSSName>
<ConnFuncAddr>aaa</ConnFuncAddr>
<DSSNum>22</DSSNum>
<isRemoved>false</isRemoved>
</Subsystem>
<Subsystem SSID="4444" ConnProfID="5555">
<SSName>BBBB</SSName>
<GenericSSName>BB</GenericSSName>
<ConnFuncAddr>bbbbbb</ConnFuncAddr>
<DSSNum>44</DSSNum>
<isRemoved>false</isRemoved>
</Subsystem>
I am having trouble getting ConnNum, IsMSPA, IsArray, and IsDDOR. I tried getting ConnNum with:
我在获取 ConnNum、IsMSPA、IsArray 和 IsDDOR 时遇到问题。我尝试使用以下方法获取 ConnNum:
//get ConnNum
Node n = doc.getFirstChild();
if (n.hasChildNodes())
System.out.println(n.getFirstChild().getNodeValue());
else
System.out.println(n.getNodeValue());
but it just returns null when im expecting 1.
但是当我期待 1 时它只返回 null。
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class test
{
public static void main(String[] args)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
for (int i = 1; i <= 8; i++)
{
Document doc = db.parse("file" + i + ".xml");
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
//get ConnNum
Node n = doc.getFirstChild();
if (n.hasChildNodes())
System.out.println(n.getFirstChild().getNodeValue());
else
System.out.println(n.getNodeValue());
NodeList listOfSubsystems = doc.getElementsByTagName("Subsystem");
int totalSubsystems = listOfSubsystems.getLength();
if (totalSubsystems == 0)
continue;
else
{
System.out.println("Total number of subsystems : " + totalSubsystems + "\n");
Dish dish = new Dish();
for(int s=0; s < listOfSubsystems.getLength() ; s++)
{
Node firstPersonNode = listOfSubsystems.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE)
{
Element firstPersonElement = (Element)firstPersonNode;
printElement(firstPersonElement, "SSName");
printElement(firstPersonElement, "GenericSSName");
printElement(firstPersonElement, "ConnFuncAddr");
printElement(firstPersonElement, "DSSNum");
printElement(firstPersonElement, "SCNum");
printElement(firstPersonElement, "SCAcronym");
printElement(firstPersonElement, "PassNum");
printElement(firstPersonElement, "FzCode");
printElement(firstPersonElement, "isRemoved");
System.out.println("------------------");
}
}
System.out.println("\n==============================");
}
}
}
catch(ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch(SAXException se)
{
se.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public static void printElement(Element a, String name)
{
NodeList elementList = a.getElementsByTagName(name);
Element b = (Element)elementList.item(0);
if (b != null)
{
NodeList list = b.getChildNodes();
System.out.println( ((Node)list.item(0)).getNodeValue().trim() );
}
}
}
回答by andyb
Perhaps the first child is not what you think it is. Whitespaceis important in XML and it is possible that the firstChild is actually a textnode.
也许第一个孩子不是你想的那样。空格在 XML 中很重要,而且 firstChild 可能实际上是一个文本节点。
Nodeshave a type and you can iterate all the children checking for Elementnode type to get a handle to the actual elements.
节点有一个类型,您可以迭代所有子节点,检查元素节点类型以获取实际元素的句柄。
Edit:This prints the values you are after. It is filtering on Elementnodes and then the first child node (the one containing the text) of each.
编辑:这将打印您所追求的值。它过滤元素节点,然后过滤每个节点的第一个子节点(包含文本的节点)。
NodeList nodeList = n.getChildNodes();
for (int j = 0; j < nodeList.getLength(); j++) {
Node childNode = nodeList.item(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(childNode.getNodeName() + " " + childNode.getFirstChild().getNodeValue());
}
}
Also, as @Steve Townsend correctly writes, you could use getTextContent()
instead of childNode.getFirstChild().getNodeValue()
if you are using Java 1.5 or above.
此外,正如@Steve Townsend 所写的getTextContent()
那样,childNode.getFirstChild().getNodeValue()
如果您使用的是 Java 1.5 或更高版本,则可以使用代替。
回答by iKushal
NodeList nodeList = n.getChildNodes();
for (int j = 0; j < nodeList.getLength(); j++) {
Node childNode = nodeList.item(j);
if (childNode instanceof Element) {
Element childElement = (Element) childNode;
System.out.println(childElement.getNodeName() + " " + childElement.getFirstChild().getNodeValue());
}
}
回答by Steve Townsend
You need to use getTextContent()here. You can use getNodeName()
first (in debug version only) to ensure you are in the correct place.
您需要在此处使用getTextContent()。您可以getNodeName()
先使用(仅在调试版本中)以确保您处于正确的位置。
getNodeValue()
returns null
if the node in hand is an element. There's a table herethat describes the results of getNode*
in each possible context.
getNodeValue()
null
如果手中的节点是一个元素,则返回。有一个表在这里描述的结果,getNode*
在每一个可能的方面。
回答by Triton Man
Try calling
试试打电话
doc.getDocumentElement()
instead of
代替
doc.getFirstChild()
回答by kingAm
If i am going to use DOM parser. I will always prefer following approach as we don't need to know every tag of xml and print them one by one.
如果我要使用 DOM 解析器。我将始终更喜欢以下方法,因为我们不需要知道 xml 的每个标签并一一打印它们。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
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 RecDOMP {
public static void main(String[] args) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
// replace following path with your input xml path
Document doc = db.parse(new FileInputStream(new File ("D:\ambuj\input.xml")));
// replace following path with your output xml path
File OutputDOM = new File("D:\ambuj\outapip1.txt");
FileOutputStream fostream = new FileOutputStream(OutputDOM);
OutputStreamWriter oswriter = new OutputStreamWriter (fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
// if file doesnt exists, then create it
if (!OutputDOM.exists()) {
OutputDOM.createNewFile();}
visitRecursively(doc,bwriter);
bwriter.close(); oswriter.close(); fostream.close();
System.out.println("Done");
}
public static void visitRecursively(Node node, BufferedWriter bw) throws IOException{
// get all child nodes
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
// get child node
Node childNode = list.item(i);
if (childNode.getNodeType() == Node.TEXT_NODE)
{
//System.out.println("Found Node: " + childNode.getNodeName()
// + " - with value: " + childNode.getNodeValue()+" Node type:"+childNode.getNodeType());
String nodeValue= childNode.getNodeValue();
nodeValue=nodeValue.replace("\n","").replaceAll("\s","");
if (!nodeValue.isEmpty())
{
System.out.println(nodeValue);
bw.write(nodeValue);
bw.newLine();
}
}
visitRecursively(childNode,bw);
}
}
}