读取xml文件内部属性
1、获取xml文本,并读取内容
这里提供两种方法:
方法一:这种方法适用于本地获取工程中的路径,通过读取文件的方式得到的document。
/**
* SdmEditorPlugin为插件工程的工程名
* 设置默认值,读取模板test-entry-dictionary.xml
* 此模板的位置:SdmEditorPlugin/conf/test-entry-dictionary.xml
*/
static {
// 创建解析器
SAXReader reader = new SAXReader();
try {
// 通过解析器将xml读取到内存中,生成对象树
entrysDoc = reader.read(new FileInputStream(
SdmEditorPlugin.getDefault().getBundle().getLocation().replace("reference:file:/", "")
+ "conf/test-entry-dictionary.xml"));
} catch (FileNotFoundException | DocumentException e) {
logger.error("文件读取异常!" + e.getMessage());
}
}
方法二:这种方法适用于产品求路径,是通过读流的方式得到document,一般使用这种方法比较好。
public static Document defaultEntrysDoc;
/**
* 设置默认值,读取模板test-entry-dictionary.xml
*/
static {
try {
// 创建解析器
SAXReader reader = new SAXReader();
//获取文件流
URL url = SdmEditorPlugin.getDefault().getBundle().getEntry("conf/test-entry-dictionary.xml");
InputStream is = url.openStream();
defaultEntrysDoc = reader.read(is);
} catch (IOException | DocumentException e) {
logger.error("文件读取异常!" + e.getMessage());
}
}
2、获取xml文件中的某一个标签:Label
Element labelEle = (Element) entrysDoc.selectSingleNode("./dictionary/component[@id='Label']");
***./dictionary:根标签root
/component:子标签
[@id='Label']":子标签的属性(id)的值是Label
3、循环遍历xml文本的Label标签
for (Object key : labelEle.elements()) {
Element keyEntry = (Element) key;
XXXXXXX具体应用
}
-----下面是xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<dictionary
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../xsd/entry-dictionary.xsd">
<!--标签Label ok -->
<component id="Label">
<property id="id" value="" isExpress="false" />
<property id="text" value="标签" isExpress="false" />
<property id="visible" value="true" isExpress="true" />
<property id="align" value="left" isExpress="false" />
<property id="style" value="" isExpress="false" />
</component>
<!-- guangzhou 侧导航栏 SideNav -->
<component id="SideNav">
<property id="id" value="" isExpress="false" />
<property id="layout" value="xy" isExpress="false" />
<property id="collapseParent" value="" isExpress="false" />
<property id="background" value="0,0,0" isExpress="false" />
<property id="style" value="" isExpress="false" />
<property id="class" value="" isExpress="false" />
</component>
<!--图表ECharts ok -->
<component id="ECharts">
<property id="id" value="" isExpress="false" />
<property id="text" value="图表" isExpress="false" />
<property id="ade" value="" isExpress="true" />
<property id="visible" value="true" isExpress="true" />
<property id="chartType" value="line" isExpress="false" />
<property id="style" value="" isExpress="false" />
</component>
</dictionary>
java读取xml还有很多方法,此法只是个人在做插件开发使用的比较便捷的方法,仅作为个人记录和他人参考。