10

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

有什么帮助吗?

4

6 回答 6

15

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

于 2012-08-10T14:17:42.790 回答
5
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Description").InnerText = "My Desciption";
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location").InnerText = "My Location";
于 2014-11-12T01:57:13.420 回答
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);
于 2012-08-10T14:32:04.873 回答
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);
于 2012-08-10T14:36:59.420 回答
1

在您的 SelectSingleNode 方法中,您需要提供一个 XPath 表达式来查找您要选择的节点。如果您使用 Google XPath,您会发现很多相关资源。

http://www.csharp-examples.net/xml-nodes-by-name/

如果您需要将这些添加到每个节点,您可以从顶部开始并遍历所有子节点。

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.aspx

于 2012-08-10T14:21:25.093 回答
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 
于 2015-08-13T10:34:10.903 回答