[Android][筆記]簡化自製版XML讀寫Lib with 超好用tool(org.w3c.dom.Node)

  • 988
  • 0

摘要:[Android][筆記]簡化自製版XML讀寫Lib with 超好用tool(org.w3c.dom.Node)

這麼好用的東西一定要筆記起來,似乎也Support .Net,隱約記得寫.Net 的動態Menu功能並使用XML記錄架構時也用過這個東東,

會有印象主要還是Function name也一模一樣,有空寫一套自己習慣的Lib我個人認為也是不錯的事情。所以下面放一個簡單範例,

並未作詳細測試,所以如果要用可能要排除一點ERROR XD。

 

目的: 在設備中讀寫XML檔,ex.如果想使用DB,可以將設定檔寫在XML檔中,再做存取設定

public class XMLHelper2 {
public static final String TAG = "XMLHelper2";
private static String xmlPath = "/sdcard/Project/MyPath/Settings.xml";
public static Document document =null;
 
public XMLHelper2() throws ParserConfigurationException, SAXException, IOException  {
   if(document==null)
   init();
}
public static void setXMLPath(String path)
{
   xmlPath=path;
}
 
public static String getXMLPath()
{
   return xmlPath;
}
 
public static void init() throws ParserConfigurationException, SAXException, IOException
{
   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
   .newInstance();
   DocumentBuilder documentBuilder = documentBuilderFactory
   .newDocumentBuilder();
   document = documentBuilder.parse(new File(xmlPath));
}
 
// 取得某個Node下面ChildNode裡,回傳特定tagName及Attribute Value的Node
private static Node Help_getChildNodes(String tagName,Node Node, String[] Attr, String[] AttrVal) {
   org.w3c.dom.Element element = (org.w3c.dom.Element) Node;
   NodeList ls = element.getElementsByTagName(tagName);
   if(ls==null)
      return null;
   for (int i = 0; i < ls.getLength(); i++) {
      boolean pass = true;
      for (int j = 0; j < Attr.length; j++) {
          if (!Help_getNodeAttr(ls.item(i), Attr[j]).equals(AttrVal[j]))
             pass = false;
          continue;
      }
     if (pass)
        return ls.item(i);
  }
  return null;
}
 
//取得特定Node的Attribute
public static String Help_getNodeAttr(Node Node, String Attr) {
   if (Node == null)
        return null;
   NamedNodeMap attributes = Node.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
       Attr attr = (Attr) attributes.item(i);
       if(attr.getNodeName().trim().equals(Attr.trim()))
           return attr.getNodeValue();
   }
   return null;
}
 
//取得Node的值
public static String Help_getNodeValueByName(Node node, String NodeName) {
   NodeList nodes = node.getChildNodes();
   for (int i = 0; i < nodes.getLength(); i++) {
      Node element = nodes.item(i);
      if (NodeName.equals(element.getNodeName())) {
          return element.getTextContent();
      }
   }
   return "";
}
 
//更新Node
public static NodeList updateNode(NodeList nodes,String NodeName,String Value)
{
    for (int i = 0; i < nodes.getLength(); i++) {
       Node element = nodes.item(i);
       if (NodeName.equals(element.getNodeName())) {
           element.setTextContent(Value);
       }
    }
    return nodes;
}
 
public static void save() throws TransformerException
{
   // write the DOM object to the file
   TransformerFactory transformerFactory = TransformerFactory
   .newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource domSource = new DOMSource(document);
   StreamResult streamResult = new StreamResult(new File(xmlPath));
   transformer.transform(domSource, streamResult);
}
 
//設定Node Attribute
public static boolean Help_setNodeAttr(Node element, String[] AttrName, String[] AttrValue) {
   try {
      if (AttrName.length != AttrValue.length)
      throw new Exception("Node的Attribute Name長度跟Attribute Value長度不一致");
      NamedNodeMap attributes = element.getAttributes();
      // get the number of nodes in this map
      for (int i = 0; i < AttrName.length; i++) {
        Node nodeAttr = attributes.getNamedItem(AttrName[i]);
        if (nodeAttr != null) // 存在就修改
           nodeAttr.setTextContent(AttrValue[i]);
        else // 沒有就"新增"
        {
           // create attribute
           Attr genderAttribute = document.createAttribute(AttrName[i]);
          genderAttribute.setValue(AttrValue[i]);
         ((org.w3c.dom.Element) element).setAttributeNode(genderAttribute);
        }
     }
     return true;
    } catch (Exception e) {
   // TODO: handle exception
   return false;
   }
  }
}
 
XML Format 
<?xml version="1.0" encoding="utf-8"?>
<PageSettings>
    <page id="1" cols="2" rows="1">
        <view ColNo="0" RowNo="0" ColSpan="1" RowSpan="1">
            <Attributes></Attributes>
        </view>
        <view ColNo="1" RowNo="0" ColSpan="1" RowSpan="1">
            <Attributes>X</Attributes>
        </view>
    <page id="2" cols="2" rows="1">
        <view ColNo="0" RowNo="0" ColSpan="1" RowSpan="1">
           <Attributes>Y</Attributes>
        </view>
        <view ColNo="1" RowNo="0" ColSpan="1" RowSpan="1">
           <Attributes>Z</Attributes>
        </view>
   </page>
</PageSettings>
 
//使用方式---簡單範例
 
public void Test()
{
    String row="0";
    String col="1";
    String PageId="1";
    //取得該節點
    Node view=getKeyNode(PageId,col,row);
    //取得節點內容
    String AttributeValue= XMLHelper2.Help_getNodeValueByName(view,"Attributes");  //Value ==> X
    //alert AttributeValue
}
 
public Node getKeyNode(String Page,String Col,String Row) throws ParserConfigurationException, SAXException, IOException 
{
   Node root =document.getDocumentElement(); //取根節點
   //第二層Page Stage
   Node page=Help_getChildNodes("page", root,new String[]{"id"},new String[]{Page}); //找到Tagename='page' 且 id=Page的 Page層Node
   //第三層View Stage
   Node view=Help_getChildNodes("view", page,new String[]{"ColNo","RowNo"},new String[]{Col,Row}); 
   return view;
}