如何消除某些祖先的元素?

时间:2012-05-03 16:05:41

标签: c# xml linq-to-xml

我正在尝试将所有“CSS”元素的值“value”设置为“”,这是代码:

XDocument doc = XDocument.Load(fi.FullName);
XNamespace rep = "http://developer.cognos.com/schemas/report/8.0/";

List<XElement> cssElements =
    (from e in doc.Root.DescendantsAndSelf(rep + "CSS")
     where
     (
         (e.Attribute("value") != null)
     )
     select e).ToList();

//modify Attribute in elements
foreach (XElement xe in cssElements)
{
    xe.Attribute("value").Value = "";
}

但是,我不想修改这个CSS,它有祖先“交叉”和“样式”(xml如下):

<crosstab name="Crosstab1" refQuery="Query1">
<crosstabSuppress type="rows"/>
<style>
    <CSS value="border-collapse:collapse;font-family:'Times New Roman'"/>  

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解正确,可能是这样的:

...

List<XElement> cssElements =
    (from e in doc.Root.DescendantsAndSelf(rep + "CSS")
        where
        (
            (e.Attribute("value") != null) && !(e.Ancestors(rep + "style").Any() && e.Ancestors(rep + "crosstab").Any())
        )
        select e).ToList();

...

我只将其添加到您的where - 子句:

&& !(e.Ancestors(rep + "style").Any() && e.Ancestors(rep + "crosstab").Any())