我正在使用某种没有冗余的 XML
<person>
<eye>
<eye_info>
<eye_color>
blue
</eye_color>
</eye_info>
</eye>
<hair>
<hair_info>
<hair_color>
blue
</hair_color>
</hair_info>
</hair>
</person>
如您所见,子标签 eye-color 在其名称中引用了 eye,因此无需避免冗余,在将 XML 加载到数据集中后,我可以在一行中获取眼睛颜色:
dataset.ReadXml(path);
value = dataset.Tables("eye_info").Rows(0)("eye_color");
我确实意识到这不是最明智的做法,而且我现在遇到的这种情况并非不可预见。
现在,假设我必须读取以下格式的 xml:
<person>
<eye>
<info>
<color>
blue
</color>
</info>
</eye>
<hair>
<info>
<color>
blue
</color>
</info>
</hair>
</person>
所以如果我尝试这样调用它:
dataset.ReadXml(path);
value = dataset.Tables("info").Rows(0)("color");
这会存在冗余,因为使用之前的方法我只能向上一级识别 XML 中的单个字段,而“消歧器”则高于三级。
在给定上述所有(或至少几个)字段的情况下,是否有一种实用的方法可以准确无误地到达单个字段?
--[编辑]--
我提出了另一个问题,询问如何使用 linq 获取某个节点,check it out .
最佳答案
您还可以使用 Linq to XML(System.Xml.Linq 命名空间)并检索数据,如下所示
string xml = @"<persons>
<person>
<eye>
<info>
<color>blue</color>
</info>
</eye>
<hair>
<info>
<color>blonde</color>
</info>
</hair>
</person>
<person>
<eye>
<info>
<color>green</color>
</info>
</eye>
<hair>
<info>
<color>brown</color>
</info>
</hair>
</person>
</persons>";
XDocument document = XDocument.Parse(xml);
var query = from person in document.Descendants("person")
select new
{
EyeColor = person.Element("eye").Element("info").Element("color").Value,
HairColor = person.Element("hair").Element("info").Element("color").Value
};
foreach (var person in query)
Console.WriteLine("{0}\t{1}", person.EyeColor, person.HairColor);
关于c# - 避免 XML 文档中的冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2507826/