2011-09-26 1 views
1

にLINQを使用してXMLに要素を追加:私はいくつかの要素を追加するために使用したコードのこの部分を持っているXML

string xmlTarget = string.Format(@"<target name='{0}' type='{1}' layout='${{2}}' />", 
               new object[] { target.Name, target.Type, target.Layout }); 
      Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
      var xmlDoc = XElement.Load(configuration.FilePath); 
      var nlog = xmlDoc.Elements("nlog"); 

      if (nlog.Count() == 0) 
      { 
       return false; 
      } 
      xmlDoc.Elements("nlog").First().Elements("targets").First().Add(xmlTarget); 
      xmlDoc.Save(configuration.FilePath,SaveOptions.DisableFormatting); 
      configuration.Save(ConfigurationSaveMode.Modified); 
      ConfigurationManager.RefreshSection("nlog"); 
      return true; 

それはXMLにターゲットを追加することになって、問題は、それがで「<」を置き換えています「&lt;」と「>」と「&gt;」が混在しています。

どうすれば修正できますか?

注意は、nlogには注意しないでください。私はlinqtoxmlの問題を懸念しています。

+1

簡単なメモ:コードの特定の部分に注意を払わないようにする簡単な方法があります。 (if(nlog.Count()== 0) 'を使用するよりも' if(!nlog.Any()) 'を使う方が良いです。) –

答えて

4

現在、の文字列が追加されています。それがコンテンツとして追加されます。 、できれ

XElement element = XElement.Parse(xmlTarget); 

または代わりにそれを構築する:あなたは要素を追加したい場合は、このような第1としてそれを解析する必要があり

XElement element = new XElement("target", 
    new XAttribute("type", target.Name), 
    new XAttribute("type", target.Type), 
    // It's not clear what your format string was trying to achieve here 
    new XAttribute("layout", target.Layout)); 

を基本的に、あなたが作成するために、文字列操作を使用して自分自身を見つける場合XMLを解析して解析すると間違ったことになります。 API自体を使用してXMLベースのオブジェクトを構築します。

+0

素晴らしい、それはうまくいきます。 – Stacker

関連する問題