This is my XML file
<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>
I have three attribute values as college_name, department_name and id available in the program. So I want to go to the particular "Department" node and change the value in the comments with these three attribute values.
I'am trying to reach the node with different queries, failed so far.
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
}
This is not working at all. If you guys could suggest me the query it would help me a lot.
Presuming you want to select a single department element based on college and department names, you can find it using a query like this one:
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();
You can then replace the comment like this:
element.ReplaceNodes(new XCData("new comment"));
I think you can use System.Xml.XmlReader
to read the nodes' attribute and write it with System.Xml.XmlWriter
How to: Parse XML with XmlReader has the example of parsing and writing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.