簡體   English   中英

如何解析 android 中的 xml 文件?

[英]How to parse an xml file in android?

我有一個 XML 文件,例如

<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
   <rootfiles>
        <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>

我需要“OEBPS/content.opf”文本的full-path值。 我嘗試使用 Document builder 和 XML 解析器,但沒有結果。 如何遍歷該節點並獲取值

我使用Jackson來序列化和反序列化(解析)xml。 我為每個元素創建一個 POJO,然后根據需要使用它解析到 POJO 的注釋。 下面是一個粗略的例子。 但是兩個外部類將使用@JsonIgnoreProperties注釋忽略所有內容(除非您將其包含在 POJO 中)。 Rootfile類將使用@JacksonXmlProperty注釋解析您想要的屬性。

旁注:我不是 100% 的@JsonRootName 這就是我標記 xml 根的方式,但我的同事使用@JackonXmlRootElement(value = "...")將 xml 字符串解析為 POJO

@JsonRootName(value = "container")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Container {

  @JsonIgnoreProperties(ignoreUnknown = true)
  public class Rootfiles {

    @JsonRootName(value = "rootfile")
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Rootfile {
      
      @JacksonXmlProperty(isAttribute = true, localName = "full-path")
      private String fullPath;

      public String getFullPath() { return fullPath; }
    }
  }
}

我找到了一種訪問屬性值的方法。 我已經解釋了評論中的所有內容。

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();

 Document doc = builder.parse(file);   // We can use inputstream or uri also

 NodeList node = doc.getElementsByTagName("rootfile"); //  gets list of all nodes by specified tag name.

 Node map = node.item(0); // Getting the specific node

 NamedNodeMap namedNodeMap = map.getAttributes();  // Getting attributed of the nodes.
            
 Node file_path = namedNodeMap.getNamedItem("full-path"); // getting the partcular node attribute

 String path = file_path.getNodeValue();  // This will give the value of full-path 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM