开发者

Problems With Using String.Replace to Modify the Output of the XML Serializer

I am generating an xml file. I noticed in the file it has a tag I do not want. I am generating the xml file from the xmlSerializer object and what its doing is handling a Property on my object wrong...The proerty on my object lloks like this...

public List<ProductVarient> Varients { get; set; }

So when I serialize it, I get a structure like this

<Varients>
  <ProductVarient>
     <Name>Nick</Name>
     ......

I want just

  <AnotherProp>
     <Stuff>toys</Stuff>
  </AnotherProp开发者_开发知识库>
  <ProductVarient>
     <Name>Nick</Name>
  </ProductVarient>
  <ProductVarient>
     <Name>Jeff</Name>
  </ProductVarient>
....

So instead of trying to workaround the xmlserializer, I went with a super hack and wrote this code

 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);
    }

2 Questions

-The code I wrote wont Replace with "", it doesnt throw an exception but it doesnt work either, im not sure why? -Is there a quick better way to accomplish my problem.


Try:

s = s.Replace("<Varients>", "");
s = s.Replace("</Varients>", ""); 

String is immutable, and methods like Replace return their result instead of mutating the receiver.

UPDATE: But, a better solution, as stated by John Saunders, is to use the XmlSerializer to achieve what you want:

[XmlElement("ProductVarient")]
public List<ProductVarient> Varients { get; set; }


Instead of trying to "work around" the XmlSerializer, you should learn to use it properly.

Try placing [XmlElement] on your property:

[XmlElement]
public List<ProductVarient> Varients { get; set; }

Alternatively, you can try [XmlArray] and [XmlArrayItem] attributes. You haven't shown a good example of the XML you want (what do you want if there are multiple items in the list?), so I can't tell you which you should use.


Bad hack and should be sent to it's room, but to answer your question:

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

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

Replace returns a modified string, just using the extension doesn't do anything unless the result is returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜