使用String.Replace修改XML Serializer输出的问题

Nic*_*rca 0 c# xml xml-serialization

我正在生成一个xml文件.我在文件中注意到它有一个我不想要的标签.我正在从xmlSerializer对象生成xml文件,它正在做什么是在我的对象上处理一个属性错误...我的对象上的proerty像这样lloks ...

public List<ProductVarient> Varients { get; set; }
Run Code Online (Sandbox Code Playgroud)

因此,当我序列化它时,我得到一个这样的结构

<Varients>
  <ProductVarient>
     <Name>Nick</Name>
     ......
Run Code Online (Sandbox Code Playgroud)

我想要的

  <AnotherProp>
     <Stuff>toys</Stuff>
  </AnotherProp>
  <ProductVarient>
     <Name>Nick</Name>
  </ProductVarient>
  <ProductVarient>
     <Name>Jeff</Name>
  </ProductVarient>
....
Run Code Online (Sandbox Code Playgroud)

因此,我没有尝试解决xmlserializer,而是使用超级黑客并编写了此代码

 string s = File.ReadAllText(path);
    s.Replace("<Varients>", "");
    s.Replace("</Varients>", "");

    using (FileStream stream = new FileStream(path, FileMode.Create))
    using (TextWriter writer = new StreamWriter(stream))
    {
        writer.WriteLine("");
        writer.WriteLine(s);
    }
Run Code Online (Sandbox Code Playgroud)

2个问题

- 我写的代码不会替换为"",它不会抛出异常,但它也不起作用,我不知道为什么? - 有一个快速更好的方法来完成我的问题.

Jor*_*dão 6

尝试:

s = s.Replace("<Varients>", "");
s = s.Replace("</Varients>", ""); 
Run Code Online (Sandbox Code Playgroud)

String是不可变的,并且Replace 返回结果而不是改变接收器的方法.

更新:但是,正如John Saunders所说,更好的解决方案是使用它XmlSerializer来实现你想要的:

[XmlElement("ProductVarient")]
public List<ProductVarient> Varients { get; set; }
Run Code Online (Sandbox Code Playgroud)