如何使用属性值访问XML文件中的元素?

时间:2015-05-15 12:19:04

标签: c# linq-to-xml

这是我的XML文件

<colleges>

    <college college_name="DYPSOE">
        <departments>
            <department department_name="Computer" id="10">
            <![CDATA[I NEED TO CHANGE THIS COMMENT!]]>
            </department>
            <department department_name="Machanical" id="20">
            <![CDATA[I NEED TO CHANGE THIS COMMENT!]]>
            </department>
        </departments>
    </college>

    <college college_name="DYPSOET">
        <departments>
            <department department_name="Computer" id="10">
            <![CDATA[I NEED TO CHANGE THIS COMMENT!]]>
            </department>
            <department department_name="Machanical" id="20">
            <![CDATA[I NEED TO CHANGE THIS COMMENT!]]>
            </department>
        </departments>
    </college>

</colleges>

我有三个属性值,如程序中可用的college_name,department_name和id。所以我想转到特定的“部门”节点,并使用这三个属性值更改注释中的值。

我试图使用不同的查询到达节点,到目前为止失败了。

var node = from e in doc.Descendants("college")
           where e.Attribute("college_name").ToString() == college_name
           select (XElement)e.Elements("department");


foreach (XElement data in node)
{
    Console.WriteLine(data); //Just to look what I got
    data.Value = ""; //To change the comment section
}

这根本不起作用。如果你们可以建议我查询它会对我有很大的帮助。

2 个答案:

答案 0 :(得分:2)

假设你想根据大学和部门名称选择一个部门元素,你可以使用类似这样的查询找到它:

var query = from college in doc.Descendants("college")
            where (string) college.Attribute("college_name") == "DYPSOE"
            from department in college.Descendants("department")
            where (string) department.Attribute("department_name") == "Computer"
            select department;

var element = query.Single();

然后您可以替换这样的评论:

element.ReplaceNodes(new XCData("new comment"));

答案 1 :(得分:0)

我认为您可以使用System.Xml.XmlReader来读取节点的属性,并使用System.Xml.XmlWriter编写它。

How to: Parse XML with XmlReader有解析和写作的例子。