【发布时间】:2013-01-12 13:29:54
【问题描述】:
我有包含图像信息的 XML 数据。我的第一个目标是创建过滤后的XmlNodeList(例如,返回color == yellow 所在的所有图像)。最终目标是能够返回color == yellow 的图像名称列表(返回整个过滤的XmlNodeList 很棒,但我真的只需要该过滤列表中的一个元素,例如名称或ID) .
在我的例子中,根节点称为Images,我希望能够在每个Image 节点中进行搜索。我的 XML 数据没有 XML 属性,因此每一位数据都表示为一个元素(使颜色“黄色”成为图像的子节点,而不是图像的属性)。
XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Images xmlns="http://oec.api.opsource.net/schemas/server"
xmlns:ns9="http://oec.api.opsource.net/schemas/multigeo"
xmlns:ns5="http://oec.api.opsource.net/schemas/vip"
xmlns:ns12="http://oec.api.opsource.net/schemas/storage"
xmlns:ns6="http://oec.api.opsource.net/schemas/whitelabel"
xmlns:ns13="http://oec.api.opsource.net/schemas/manualimport"
xmlns:ns7="http://oec.api.opsource.net/schemas/datacenter"
xmlns:ns10="http://oec.api.opsource.net/schemas/reset"
xmlns:ns8="http://oec.api.opsource.net/schemas/general"
xmlns:ns11="http://oec.api.opsource.net/schemas/support"
xmlns:ns2="http://oec.api.opsource.net/schemas/directory"
xmlns:ns4="http://oec.api.opsource.net/schemas/network"
xmlns:ns3="http://oec.api.opsource.net/schemas/organization">
<Image>
<id>mcd93jf8dd</id>
<name>cat</name>
<color>yellow</color>
</Image>
<Image>
<id>d4b8l23sas</id>
<name>dog</name>
<color>yellow</color>
</Image>
</Images>
我最初的 XML 数据源是一个流。我已经找到了使用 foreach 循环遍历我的 XML 层次结构的不同级别的方法,但是我一直遇到在子节点上没有我需要的所有方法可用的问题。其他地方的建议似乎建议使用XPath 来实现我的过滤器,但我无法让它与我目前所拥有的一起工作:
C#
//'stream' previously defined as a Stream
XmlReader reader = XmlReader.Create(stream);
XmlDocument xml = new XmlDocument();
xml.Load(reader);
XmlElement root = xml.DocumentElement;
XmlNodeList images = root.ChildNodes;
foreach (XmlNode image in images) {
XmlNodeList attributes = image.ChildNodes;
foreach (XmlNode attribute in attributes) {
//do stuff
}
}
【问题讨论】: