2016-08-26 5 views
0

これは初めてのxmldocumentで作業していますが、少し失われています。目的は、XmlDocの特定の場所に挿入することです。XmlDocumentに複数の要素を挿入する

<appSettings> 
<add key="FreitRaterHelpLoc" value="" /> 
<add key="FreitRaterWebHome" value="http://GPGBYTOPSPL12/" /> 
<add key="FreitRaterDefaultSession" value="" /> 
<add key="FreitRaterTransferMode" value="Buffered" /> 
<add key="FreitRaterMaxMsgSize" value="524288" /> 
<add key="FreitRaterMaxArray" value="16384" /> 
<add key="FreitRaterMaxString" value="32768" /> 
<add key="FreitRaterSvcTimeout" value="60" /> 
</appSettings> 

は、これまでのところ、私はちょうど最初の要素

 XmlElement root = Document.CreateElement("appSettings"); 
     XmlElement id = Document.CreateElement("add"); 
     id.SetAttribute("key", "FreitRaterHelpLoc"); 
     id.SetAttribute("value", ""); 

     root.AppendChild(id); 

に焦点を当てて始めましたが、これは残りの要素を追加するための十分なのですか?例えば、これは私がラインのためのテキストのこのブロックを取得するための最良の方法だろう何InsertAfterはここに必要となるかどうかわから、または一般にはない2

 id = Document.CreateElement("add"); 
     id.SetAttribute("key", "FreitRaterWebHome"); 
     id.SetAttribute("value", "http://GPGBYTOPSPL12/"); 

     root.AppendChild(id); 

イムを持っているものである。ここでも、XMLDOC新人

+1

そうに...ですあなたのコードは動作しますか?ベストプラクティスについて質問していますか? – Kinetic

+0

ドキュメントを手動で構築するのではなく、 'Load' /' LoadXml'メソッドを使ってxmlをロードするのはなぜですか? – Pawel

答えて

1

XmlDocumentの代わりにLINQ to XMLを使用することを強くお勧めします。それは非常に良くAPIです - あなたは、単に宣言方式で文書を作成することができます。

var settings = new XElement("appSettings", 
    new XElement("add", 
     new XAttribute("key", "FreitRaterHelpLoc"), 
     new XAttribute("value", "")), 
    new XElement("add", 
     new XAttribute("key", "FreitRaterWebHome"), 
     new XAttribute("value", "http://GPGBYTOPSPL12/")), 
    new XElement("add", 
     new XAttribute("key", "FreitRaterDefaultSession"), 
     new XAttribute("value", "")) 
); 

それともでも、単純な変換宣言することにより、他のオブジェクトからその一部を生成します。

var dictionary = new Dictionary<string, string> 
{ 
    {"FreitRaterHelpLoc", ""}, 
    {"FreitRaterWebHome", "http://GPGBYTOPSPL12/"}, 
    {"FreitRaterDefaultSession", ""}, 
}; 

var keyValues = 
    from pair in dictionary 
    select new XElement("add", 
     new XAttribute("key", pair.Key), 
     new XAttribute("value", pair.Value)); 

var settings = new XElement("appSettings", keyValues); 
+0

これははるかに理にかなっており、ずっと簡単です。ありがとう –