2012-08-10 139 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