Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在XML中插入数据_C#_Linq To Xml - Fatal编程技术网

C# 如何在XML中插入数据

C# 如何在XML中插入数据,c#,linq-to-xml,C#,Linq To Xml,我需要将一些数据放入XML文件中。我可以使用XmlSerializer序列化数据,但我应该多次写入数据,所以如果我使用XmlSerializer,我会得到类似的结果 <?xml version="1.0" encoding="utf-8"?> <Address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> &l

我需要将一些数据放入XML文件中。我可以使用XmlSerializer序列化数据,但我应该多次写入数据,所以如果我使用XmlSerializer,我会得到类似的结果

 <?xml version="1.0" encoding="utf-8"?>
 <Address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <AddressId>0</AddressId>
   <Country>Test5</Country>
   <Region>Test5</Region>
   <Locality>Test5</Locality>
   <Street>Test5</Street>
   <HouseNumber>Test5</HouseNumber>
   <BuildingNumber>Test5</BuildingNumber>
   <ApartmentNumber>Test5</ApartmentNumber>
 </Address>

 <?xml version="1.0" encoding="utf-8"?>
 <Address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <AddressId>0</AddressId>
   <Country>Test6</Country>
   <Region>Test6</Region>
   <Locality>Test6</Locality>
   <Street>Test6</Street>
   <HouseNumber>Test6</HouseNumber>
   <BuildingNumber>Test6</BuildingNumber>
   <ApartmentNumber>Test6</ApartmentNumber>
 </Address> 

那么,您建议我使用什么来实现我的目标呢?

您没有将元素添加到文档中,并且类不属于
LINQ to XML
您需要:

或者您可以只保存
XElement
本身:

 xmlTree.Save("MvcApp4.xml");
XDocument xmlDocument = new XDocument();
XElement xmlTree =
        new XElement("Addresses",
         new XElement("Address", new XAttribute("Id", "1000"),
         new XElement("Country", address.Country),
         new XElement("Region", address.Region),
         new XElement("Locality", address.Locality),
         new XElement("Street", address.Street),
         new XElement("HouseNumber", address.HouseNumber),
          new XElement("BuildingNumber", address.BuildingNumber),
          new XElement("ApartmentNumber", address.ApartmentNumber)
          )
         );
xmlDocument.Add(xmlTree);
xmlDocument.Save("MvcApp4.xml");
 xmlTree.Save("MvcApp4.xml");