[英]How to parse an xml file in android?
I have an XML file like我有一个 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>
I need the full-path
value that is "OEBPS/content.opf" text.我需要“OEBPS/content.opf”文本的
full-path
值。 I tried using Document builder and XML parser but no results.我尝试使用 Document builder 和 XML 解析器,但没有结果。 How do I traverse to that node and get the value
如何遍历该节点并获取值
I've used Jackson to serialize and deserialize(parse) xml.我使用Jackson来序列化和反序列化(解析)xml。 I make a POJO for each element and then using the annotations it parses to the POJO as needed.
我为每个元素创建一个 POJO,然后根据需要使用它解析到 POJO 的注释。 The below is a rough example.
下面是一个粗略的例子。 But the the two outer classes will ignore everything(unless you include it in the POJO) using the
@JsonIgnoreProperties
annotations.但是两个外部类将使用
@JsonIgnoreProperties
注释忽略所有内容(除非您将其包含在 POJO 中)。 And the Rootfile
class will parse the attribute you want using the @JacksonXmlProperty
annotation. Rootfile
类将使用@JacksonXmlProperty
注释解析您想要的属性。
Sidenote: I'm not 100% on the @JsonRootName
.旁注:我不是 100% 的
@JsonRootName
。 That is how I marked the xml root, but my colleague parsed the xml string to POJO using @JackonXmlRootElement(value = "...")
这就是我标记 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; }
}
}
}
I found a way to access the attribute values.我找到了一种访问属性值的方法。 I have explained all the lines in the comments.
我已经解释了评论中的所有内容。
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.