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

LINQToXMLを使用する:)

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 に答える
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 に答える
1

SelectSingleNode メソッドでは、選択しようとしているノードを見つけるために XPath 式を提供する必要があります。XPath を Google で検索すると、これに関する多くのリソースが見つかります。

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 に答える