2012-08-10 76 views
8

我有一个XML(这正是它看起来像):如何改变XML节点值

<PolicyChangeSet schemaVersion="2.1" username="" description=""> 
    <Attachment name="" contentType=""> 
     <Description/> 
     <Location></Location> 
    </Attachment> 
</PolicyChangeSet> 

这是在用户的机器上。

我需要为每个节点添加值:用户名,说明,附件名称,内容类型和位置。

这是我到目前为止有:

string newValue = string.Empty; 
      XmlDocument xmlDoc = new XmlDocument(); 

      xmlDoc.Load(filePath); 
      XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node.Attributes["username"].Value = AppVars.Username; 
      node.Attributes["description"].Value = "Adding new .tiff image."; 
      node.Attributes["name"].Value = "POLICY"; 
      node.Attributes["contentType"].Value = "content Typeeee"; 

      //node.Attributes["location"].InnerText = "zzz"; 

      xmlDoc.Save(filePath); 

任何帮助吗?

回答

13

使用XPath。 XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet");选择你的根节点。

+1

奏效:) ......我只能接受你的答案在10分钟左右。 thx Jan! – Testifier 2012-08-10 14:19:50

+0

虽然我会如何为“位置”添加值?它只是在<> ......之间? – Testifier 2012-08-10 14:21:47

+0

任何时候:)看看XmlNode的'InnerText'属性。 – Jan 2012-08-10 14:23:45

3

本明白了 -

xmlDoc.Load(filePath); 
      XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node.Attributes["username"].Value = AppVars.Username; 
      node.Attributes["description"].Value = "Adding new .tiff image."; 

      node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment"); 
      node.Attributes["name"].Value = "POLICY"; 
      node.Attributes["contentType"].Value = "content Typeeee"; 
xmlDoc.Save(filePath); 
2

使用LINQ XML :)

XDocument doc = XDocument.Load(path); 
IEnumerable<XElement> policyChangeSetCollection = doc.Elements("PolicyChangeSet"); 

foreach(XElement node in policyChangeSetCollection) 
{ 
    node.Attribute("username").SetValue(someVal1); 
    node.Attribute("description").SetValue(someVal2); 
    XElement attachment = node.Element("attachment"); 
    attachment.Attribute("name").SetValue(someVal3); 
    attachment.Attribute("contentType").SetValue(someVal4); 
} 

doc.Save(path); 
2
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Description").InnerText = "My Desciption"; 
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location").InnerText = "My Location"; 
0
For setting value to XmlNode: 
XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node["username"].InnerText = AppVars.Username; 
      node["description"].InnerText = "Adding new .tiff image."; 
      node["name"].InnerText = "POLICY"; 
      node["contentType"].InnerText = "content Typeeee"; 

For Getting value to XmlNode: 
username=node["username"].InnerText