i want to create xml file using linq to xml like this
<?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>
i try this code but give me an Root element is missing.
exception
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);
}
}
}
You can simply save XElement
which is root. And you don't need to load anything when you are creating new xml file:
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);
}
}
}
If you want to use XDocument (which is not needed in your case), then just create new XDocument instead of loading non-existing file:
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);
Well, you try to "read/parse" a new empty document with XDocument.Load()
File.Create(path).Close();
XDocument document = XDocument.Load(path);
and XDocument.Load()
wants a correct xml file... which he has not (file is empty) !
So you could just do
var document = new XDocument();
//...
document.Save(path);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.