Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.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# 如何重新序列化修改后的对象并插入回XDocument?_C#_.net_Xml Serialization_Linq To Xml - Fatal编程技术网

C# 如何重新序列化修改后的对象并插入回XDocument?

C# 如何重新序列化修改后的对象并插入回XDocument?,c#,.net,xml-serialization,linq-to-xml,C#,.net,Xml Serialization,Linq To Xml,我在XDocument中有一组嵌套的对象,如下所示: <Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="FooInfo"> <Name>Red</Name> <Record xsi:type="BarInfo"> <Name>Tomato&

我在XDocument中有一组嵌套的对象,如下所示:

<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="FooInfo">
  <Name>Red</Name>
  <Record xsi:type="BarInfo">
    <Name>Tomato</Name>
    <Record xsi:type="BazInfo">
      <Name>Juice</Name>
    </Record >
    <Record xsi:type="BazInfo">
      <Name>Sauce</Name>
    </Record >
  </Record >
</Record >
BazInfo类看起来像:

class BazInfo : IInfo {  
    [XmlElement]
    string Name { get; set; }
    [XmlElement]
    string Manufacturer { get; set; }
}
最初序列化BazInfo时,没有包含Manufacturer属性(即没有元素),因为没有分配任何值。这不是一个问题,只是当我想赋值时,我不能只在子代或元素集合中查找该元素。因此,我反序列化对象并指定值:

bi.Manufacturer = "Acme"; 
// re-serialize element
s.Serialize(e.CreateWriter(), bi);
当我尝试重新序列化对象时,我收到一个例外:

System.InvalidOperationException:生成 XML文档。-->System.InvalidOperationException: 无法对使用创建的写入程序调用WriteStartDocument ConformanceLevel.Fragment

我希望能够将对象插入回它所属的位置:

  <Record xsi:type="BarInfo">
    <Name>Tomato</Name>
    <Record xsi:type="BazInfo">
      <Name>Juice</Name>
    </Record >
    <Record xsi:type="BazInfo">
      <Name>Sauce</Name>
      <Manufacturer>Acme</Manufacturer>
    </Record >
  </Record >
有什么想法吗

我知道如果找不到,我可以添加一个元素制造商,然后分配值,但这似乎很容易被破坏

  <Record xsi:type="BarInfo">
    <Name>Tomato</Name>
    <Record xsi:type="BazInfo">
      <Name>Juice</Name>
    </Record >
    <Record xsi:type="BazInfo">
      <Name>Sauce</Name>
      <Manufacturer>Acme</Manufacturer>
    </Record >
  </Record >