如何更改XML节点值

12

我有一个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);

有人可以帮忙吗?

6个回答

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

1
那个有效 :) ... 不过我只能在10分钟后接受你的答案。谢谢,Jan! - JJ.
我该如何为“location”添加一个值呢?它只是在<> </>之间...?? - JJ.
顺便说一下,用户名和描述都正常工作,但是当我需要更改附件名称时出现错误,我已经编辑了我的帖子并附上了代码,请看一下。 - JJ.
我仍然无法在<location> VALUE </location>之间设置值。我以为node.Attributed["location"].InnerText = "location"会起作用..但是没有成功:( - JJ.
1
位置是一个节点,而不是属性。此外,XPath区分大小写。node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location"); 然后 node.InnerText = "myLocation" 是在这里前进的方式。 - Jan
显示剩余2条评论

6
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Description").InnerText = "My Description";
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location").InnerText = "My Location";

4

使用以下方式获取 -

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);

4
使用LINQ To 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);

1

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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接