2013-01-23 67 views
2

我想使用LINQ到这样的XML缺失根元素。例外

<?xml version="1.0" encoding="utf-8"?> 
<Configuration> 
    <Settings> 
    <UseStreemCodec value="false" /> 
    <SipPort value="5060"/> 
    <H323Port value="1720" /> 
    </Settings> 

    <IncomingCallsConfiguration> 
    </IncomingCallsConfiguration> 

    <OutGoingCallsConfiguration> 
    <Devices> 
    </Devices> 
    </OutGoingCallsConfiguration> 

    </Configuration> 

我试试这个代码,但给我一个Root element is missing.例外

public void CreatXmlConfigurationFileIfNotFoundWithDefultTags(string path) 
     { 
      if (!File.Exists(path)) 
      { 
       try 
       { 
        File.Create(path).Close(); 
        XDocument document = XDocument.Load(path); 
        var setting = new XElement("Settings", 
         new XElement("UseStreemCodec", new XAttribute("value", "false")), 
         new XElement("SipPort", new XAttribute("value", "5060")), 
         new XElement("H323Port", new XAttribute("value", "1720")) 
         ); 

        document.Add(new XElement("Configuration", setting, 
         new XElement("IncomingCallsConfiguration"), 
         new XElement("OutGoingCallsConfiguration"))); 

        document.Save(path); 
       } 
       catch (Exception e) 
       { 
        Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message); 
       } 
      } 
     } 

回答

3

你可以简单地保存XElement这是根目录中创建XML文件。而你并不需要在您创建新的XML文件来加载任何东西:

public void CreatXmlConfigurationFileIfNotFoundWithDefultTags(string path) 
{ 
    if (!File.Exists(path)) 
    { 
     try 
     { 
      var setting = new XElement("Settings", 
       new XElement("UseStreemCodec", new XAttribute("value", "false")), 
       new XElement("SipPort", new XAttribute("value", "5060")), 
       new XElement("H323Port", new XAttribute("value", "1720")) 
      ); 

      var config = new XElement("Configuration", setting, 
       new XElement("IncomingCallsConfiguration"), 
       new XElement("OutGoingCallsConfiguration"))); 

      config.Save(path); // save XElement to file 
     } 
     catch (Exception e) 
     { 
      Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message); 
     } 
    } 
} 

如果你想使用的XDocument(它不需要你的情况),那么只需要创建新的XDocument,而不是装载非现有的文件:

XDocument document = new XDocument(); 
var setting = new XElement("Settings", 
    new XElement("UseStreemCodec", new XAttribute("value", "false")), 
    new XElement("SipPort", new XAttribute("value", "5060")), 
     new XElement("H323Port", new XAttribute("value", "1720")) 
    ); 

document.Add(new XElement("Configuration", setting, 
    new XElement("IncomingCallsConfiguration"), 
    new XElement("OutGoingCallsConfiguration"))); 

document.Save(path); 
3

嗯,你尝试 “读/解析” 与XDocument.Load()一个新的空文件

File.Create(path).Close(); 
XDocument document = XDocument.Load(path); 

XDocument.Load()想要一个正确的xml文件...他有ñ ot(文件为空)!

所以,你可以只是做

var document = new XDocument(); 
//... 
document.Save(path);