0

我的 xml 看起来像这样:

        <root>
            <x a1 = "abc">
                <y a2 = "def"> 
                    <z value1 = 5 value2 = 10 value3 = 15/>             
                </y>
            </x>
        </root>

我的主要代码:

static void Main(string[] args)
{
    int value;
    IEnumerable<XElement> xs = from x in xDoc.Descendants("x")
                               where (string)x.Attribute("a1") == "abc"
                               select x;
    IEnumerable<XElement> ys = from y in xs.Descendants("y")
                               where (string)y.Attribute("a2") == "def"
                               select time;
    IEnumerable<XElement> zs = from z in ys.Descendants("z")
                               where z.Attribute == value1
                               select z;
}

我正在尝试根据特定条件将 int 值设置为节点 z 的值 1、2 或 3。当我尝试在节点 z 中过滤所需的值时,会出现我的问题。有人可以解释我如何将节点 z 的匹配值分配给 int 值。

4

3 回答 3

0

如果我理解正确,您想选择 z 节点的一些元素:

string value = "value1";

var query = xDoc.Descendants("x")
                .Where(x => (string)x.Attribute("a1") == "abc")
                .Descendants("y")
                .Where(y => (string)y.Attribute("a2") == "def")
                .Descendants("z")
                .Select(z => (string)z.Element(value))
                .Select(s => Int32.Parse(s.Replace("\"", "")));

查询结果 - IEnumerable<int>。如果您确定会有一个值,或者您需要第一个值,您可以申请SingleFirst

另外我不明白为什么你保持 values as"5"而不是 simple 5

于 2012-12-01T14:12:55.587 回答
0

您可以在此处使用 XPath (System.Xml.XPath)

var elemZ = xDoc.XPathSelectElement("//x[@a1='abc']/y[@a2='def']/z");

int val1 = (int)elemZ.Attribute("value1");

将您的 xml 更正为 <z value1 = "5" value2 = "10" value3 = "15" />

您甚至可以通过单个 linq 获取所有属性值

var values = elemZ.Attributes().Select(a => (int)a).ToList();
于 2012-12-01T14:31:26.517 回答
0

我认为你需要这样的东西:

 IEnumerable<XElement> z's = from z in y.Descendants("z")
                                  where z.Attribute("value1") != null
                                  select z; 
于 2012-12-01T14:53:50.377 回答