考虑具有XML

时间:2015-05-11 11:25:08

标签: c# xml

我想从xml中搜索具有section属性的内容 我的控制器代码是:

xd.LoadXml(p.text);
XmlNodeList txt = xd.GetElementsByTagName("Texts");
for (int i = 0; i < txt.Count; i++)
{
    XmlNode nd = txt.Item(i);
    if (nd.HasChildNodes)
    {
        XmlNodeList cnd = nd.ChildNodes;
        foreach (XmlNode n in cnd)
        {
            if (SectionName == n.Attributes["section"].Value)
            {
                Text text = new Text()
                {
                    AudioList = n.Attributes["audio"].Value
                };
                newroom.text.Add(text);
            }
        }
    }
}

和XML就像:

<Texts>
    <Text group="Outbuilding0">blank</Text>
    <Text group="Study0" audio="abc.wav" section="Walls and skirting">[[Walls and skirting]] </Text>
    <Text group="Study0" audio="c.wav" section="Walls and skirting">[[Walls and skirting]] </Text>
</Texts>

从仅具有部分属性的搜索开始...任何建议PLZ?

2 个答案:

答案 0 :(得分:0)

LINQ to XML将使这更容易:

var doc = XDocument.Parse(p.text);

var texts = doc.Descendants("Text")
    .Where(e => (string)e.Attribute("section") == SectionName)
    .Select(e => new Text
    {
        AudioList = (string)e.Attribute("audio")
    });

foreach (var text in texts)
{
    newroom.text.Add(text);
}

在查询语法中可能更具可读性:

var texts = from text in doc.Descendants("Text")
            let section = (string)text.Attribute("section")
            where section == SectionName
            select new Text
            {
                AudioList = (string)text.Attribute("audio")
            };

答案 1 :(得分:0)

您可以尝试使用SelectNodes()传递合适的xpath作为参数:

XmlNodeList txt = xd.SelectNodes("//Texts/Text[@section]");
foreach(XmlNode t in txt)
{
    Text text = new Text()
    {
        AudioList = t.Attributes["audio"].Value
    };
    newroom.text.Add(text);
}

在xpath上方读取:选择具有属性<Text>的所有section,并且是<Texts>的直接子项。