首先xml是这样的:
<config>
<Fonts>
<Language name="en" >
<Default>MHeiHK-Medium.OTF</Default>
<Title>MHeiHK-Bold.OTF</Title>
<ChatName>MHeiHK-Bold.OTF</ChatName>
<ChatContent>MHeiHK-Light.otf</ChatContent>
</Language>
<Language name="zh_HK" >
<Default>zhongyuanti.ttc</Default>
<Title>zhongteyuanti.ttc</Title>
<ChatName>licuyuan.ttc</ChatName>
<ChatContent>zhongyuanti.ttc</ChatContent>
</Language>
</Fonts>
</config>
主要类:NodeList、Element
主要方法:NodeList:item(index) 得到第几个节点例如上面Language就有两个节点,通过这个方法拿到第几个Language
Element:getElementsByTagName(TagName) 根据标签名(如Fonts、Language、Default、Title...)得到节点列表,该方法返回NodeList对象
getAttribute(AttributeName) 获得属性的值,如Language带有属性name
============= 主要代码部分 =====================
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
InputStream inputStream = null;
try {
builder = factory.newDocumentBuilder();
inputStream = CommonHelper.activity.getResources().getAssets()
.open("configxml/config.xml");
document = builder.parse(inputStream);
Element fontRoot = (Element) document.getDocumentElement()
.getElementsByTagName("Fonts").item(0); // 从这里开始得到Fonts节点(因为得到的是NodeList,所以取第一个节点后强制转换为Element类)
NodeList nodes = fontRoot.getElementsByTagName("Language");// 获取Language的节点列表
String[] fontFamilies = { "Default", "Title", "ChatName",
"ChatContent" };// Language下的节点集合,每个Language下都带有4个节点
for (int i = 0; i < nodes.getLength(); i++) {
Element langElement = (Element) nodes.item(i);
Locale locale = new Locale(langElement.getAttribute("name"));// 获得Element的Name属性值
HashMap<String, Typeface> typefaceMap = new HashMap<String, Typeface>();
for (String fontFamily : fontFamilies) {
Element defElement = (Element) langElement
.getElementsByTagName(fontFamily).item(0);
String fontFileName = defElement.getFirstChild()
.getNodeValue();
if (!typefaceMap.containsKey(fontFamily)) {
typefaceMap.put(fontFamily, Typeface.createFromAsset(
CommonHelper.activity.getResources()
.getAssets(), "Fonts/" + fontFileName));
}
}
}
} catch (Exception ex) {
NotificationHelper.showText(CommonHelper.activity, ex.getMessage());
}