gpt4 book ai didi

c# - 缺少根元素。异常(exception)

转载 作者:行者123 更新时间:2023-12-03 23:45:30 26 4
gpt4 key购买 nike

我想像这样使用 linq to xml 创建 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. 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);
}
}
}

最佳答案

您可以简单地保存 XElement 这是根。并且在创建新的 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);

关于c# - 缺少根元素。异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com