我有一个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);
任何帮助?
答案 0 :(得分:13)
使用XPath。 XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet");
选择您的根节点。
答案 1 :(得分: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 :(得分:2)
使用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);
答案 3 :(得分:2)
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Description").InnerText = "My Desciption";
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location").InnerText = "My Location";
答案 4 :(得分:0)
在SelectSingleNode方法中,您需要提供一个XPath表达式,找到您要选择的节点。如果你使用谷歌XPath,你会发现很多资源。
http://www.csharp-examples.net/xml-nodes-by-name/
如果您需要将这些添加到每个节点,您可以从顶部开始并遍历所有子节点。
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.aspx
答案 5 :(得分: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