2014-10-28 2 views
0

XML 파일의 값을 업데이트하는 루틴을 작성하려고하고 있습니다. 다음은 XML의 예입니다.XML에서 중첩 값 업데이트

 <?xml version="1.0" encoding="utf-8"?> 
<!-- This file is generated by the GPS_Client program. --> 
<Sites> 
    <Site> 
    <Id>A</Id> 
    <add key="landingName" value="Somewhere" /> 
    <add key="landingLat" value="47.423719" /> 
    <add key="landingLon" value="-123.011364" /> 
    <add key="landingAlt" value="36" /> 
    </Site> 
    <Site> 
    <Id>B</Id> 
    <add key="landingName" value="Somewhere Else" /> 
    <add key="landingLat" value="45.629160" /> 
    <add key="landingLon" value="-128.882934" /> 
    <add key="landingAlt" value="327" /> 
    </Site> 
</Sites> 

키의 나머지 부분은 동일한 이름으로 업데이트하지 않고 특정 키를 업데이트해야합니다. 현재 코드는 다음과 같습니다.

 private void UpdateOrCreateAppSetting(string filename, string site, string key, string value) 
{ 
    string path = "\"@" + filename + "\""; 
    XDocument doc = XDocument.Load(path); 
    var list = from appNode in doc.Descendants("appSettings").Elements() 
      where appNode.Attribute("key").Value == key 
      select appNode; 
    var e = list.FirstOrDefault(); 

    // If the element doesn't exist, create it 
    if (e == null) { 
     new XElement(site, 
      new XAttribute(key, value)); 
    // If the element exists, just change its value 
    } else { 
     e.Element(key).Value = value; 
     e.Attribute("value").SetValue(value); 
    } 
} 

나는 사이트, ID 및 키를 어떤 식 으로든 연결해야한다고 가정하지만 어떻게 수행되는지는 알 수 없습니다.

+0

내부에서 업데이트해야합니다. 어떤 행동을보고 있습니까? 현재는 XML을 어디에서나 작성하거나 리턴하지 않으므로 디버거를 사용하는 것이 유일한 방법입니다. – Dweeberly

+1

코드가 XML과 일치하지 않습니다. 'Descendants ("appSettings")'당신이 보여주는 데모 XML에는'appSettings'의 노드가 없습니다. –

답변

0

this XmlLib을 사용하면 자동으로 존재하지 않는 노드를 만들 수 있습니다.

private void UpdateOrCreateAppSetting(string filename, string site, 
             string key, string value) 
{ 
    string path = "\"@" + filename + "\""; 
    XDocument doc = XDocument.Load(path); 
    XPathString xpath = new XPathString("//Site[Id={0}]/add[@key={1}]", site, key); 
    XElement node = doc.Root.XPathElement(xpath, true); // true = create if not found 
    node.Set("value", value, true); // set as attribute, creates attribute if not found 
    doc.Save(filename); 
}