public class ParseXML
{
public static void main(String args[])
{
try
{
//获取到配置文件
String configFileName = "src/example.xml";
File f = new File(configFileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
db = factory.newDocumentBuilder();
Document documents;
//将配置文件解析进来
documents = db.parse(f);
[color=green] //按照bean标签读取参数
NodeList nl = documents.getElementsByTagName("bean");
for (int i = 0; i < nl.getLength(); i++)
{
if (documents.getElementsByTagName("id").item(i) != null)
{
System.out.println(documents.getElementsByTagName("id").item(i).getFirstChild().getNodeValue());
}
}[/color]
//获取配置文件参数
Element rootElement = documents.getDocumentElement();
NodeList children = rootElement.getChildNodes();
int childSize = children.getLength();
for (int i = 0; i < childSize; i++)
{
Node childNode = children.item(i);
if (childNode instanceof Element)
{
Element child = (Element)childNode;
final String nodeName = child.getNodeName();
if ("bean".equals(nodeName))
{
String firstCondition = child.getAttribute("firstCondition");
String className = child.getAttribute("class");
String serviceId = child.getAttribute("id");
}
}
}
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这里提供的方法可以解析两种格式的XML文件:
<?xml version="1.0" encoding="UTF-8" ?>
<struts>
<bean serviceId="testExample" firstCondition="Pudge" class="com.kewen.123456" />
<bean serviceId="ZXC" firstCondition="NeverMore" class="com.kewen.123456" />
</struts>
另一种:
<bean>
<serviceId>1234</serviceId>
<firstCondition>puck</firstCondition>
<class>com.kewen.kkkk</class>
</bean>
绿色java代码用于解析第二种xml格式。