在我的情况下,我想在给定的xml架构中添加多个根节点。因此,我必须通过在xml文件中附加先前的内容,多次将不同的用户元素与其子节点追加。我的问题是如何添加多个根元素? (我可以添加一个根元素,但不知道如何添加下一个)。
这是xml架构
<?xml version="1.0" encoding="utf-8"?>
<SessionId>
<Scource>
<User username="AB">
<DOB>25/5/1980</DOB>
<FirstName>AVS</FirstName>
<LastName>WDW</LastName>
<Location>FWAWE</Location>
</User>
<User username="AqB">
<DOB>25/5/1980</DOB>
<FirstName>AVS</FirstName>
<LastName>WDW</LastName>
<Location>FWAWE</Location>
</User>
</Scource>
</SessionId>
这是我的C#代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace FilteringNightwing
{
class Test
{
static void Main(string[] args) {
string fileLocation = "clients.xml";
if (!File.Exists(fileLocation))
{
XmlTextWriter writer = new XmlTextWriter(fileLocation, null);
writer.WriteStartElement("SessionId");
writer.WriteEndElement();
writer.Close();
}
// Load existing clients and add new
XElement xml = XElement.Load(fileLocation);
xml.Add(new XElement("User",
new XAttribute("username", "AqB"),
new XElement("DOB", "25/5/1980"),
new XElement("FirstName", "AVS"),
new XElement("LastName", "WDW"),
new XElement("Location", "FWAWE")));
xml.Save(fileLocation);
}
}
}
答案 0 :(得分:0)
您不能拥有多个根节点。解析以下内容会给您一个错误。
XElement root = XElement.Parse("<a></a><b></b>");
这也会出错:
XElement root = XElement.Parse("<a></a><a></a>");
如果您想要多个子节点到根节点,那就完全没问题了。您可以拥有相同名称或不同的节点。如:
<a>
<b />
<c>
<d />
</c>
<b />
</a>
将新用户添加到Scource
:
XElement xml = XElement.Load(fileLocation);
XElement scource = xml.Element("Scource"); // Find Scource here
scource.Add(new XElement("User", // Add new user to Scource here
new XAttribute("username", "AqB"),
new XElement("DOB", "25/5/1980"),
new XElement("FirstName", "AVS"),
new XElement("LastName", "WDW"),
new XElement("Location", "FWAWE")));
xml.Save(fileLocation);
答案 1 :(得分:0)
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><SessionId><Source></Source></SessionId>";
XDocument doc = XDocument.Parse(xml);
XElement source = doc.Descendants("Source").FirstOrDefault();
source.Add(new XElement("User", new object[] {
new XAttribute("username", "AqB"),
new XElement("DOB", "25/5/1980"),
new XElement("FirstName", "AVS"),
new XElement("LastName", "WDW"),
new XElement("Location", "FWAWE")
}));
}
}
}