[英]Add a new element with node childs in a XML file in c#
I have a xml that is something like this: 我有这样的xml:
<Servers>
<MyNewServer>
<Host>10.10.10.2</Host>
<Port>12</Port>
<User>MyUser</User>
<Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
</MyNewServer>
</Servers>
I'm trying to add a new server below of "NyNewServer" label and add the same child elements in blank (Host, Port, User and Password). 我正在尝试在“ NyNewServer”标签下方添加新服务器,并在空白处添加相同的子元素(主机,端口,用户和密码)。
I'm adding now a new element of server but is not with the correct format is displayed horizontal instead of vertically, and I'm not sure how to add the child elements in blank. 我现在要添加服务器的新元素,但格式不正确,而是水平显示而不是垂直显示,而且我不确定如何将子元素添加为空白。
Any idea? 任何想法? I have this:
我有这个:
public void XmlNewInterface(string Server)
{
//Temporal Solution
xmldoc.Load(XMLInterfacesFile);
XmlElement record = xmldoc.CreateElement(Server);
record.InnerText = Guid.NewGuid().ToString();
xmldoc.DocumentElement.AppendChild(record);
xmldoc.Save(XMLInterfacesFile);
}
Thanks 谢谢
I prefer Linq
to Xml
, it simplifies building/constructing Xml. 我更喜欢
Linq
而不是Xml
,它简化了Xml
构建/构造。 You just need these lines. 您只需要这些行。
var doc = XDocument.load(inputfile);
doc.Descendants("Servers").First()
.Add( new XElement("OneMoreServer", new [] {
new XElement("Host"),
new XElement("Port"),
new XElement("MyUser"),
new XElement("Password")
}));
Output 输出量
<Servers>
<MyNewServer>
<Host>10.10.10.2</Host>
<Port>12</Port>
<User>MyUser</User>
<Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
</MyNewServer>
<OneMoreServer>
<Host />
<Port />
<MyUser />
<Password />
</OneMoreServer>
</Servers>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.