简体   繁体   中英

Serialize class variable as xml without creating a new element

I have two classes, A and B. A has an instance of B, and when serializing A, I want B to be at the same level as A and not a sub element.

So I want the resulting xml to become

<a>
      <avalue>a</avalue>
      <bvalue>b</bvalue>
    </a>

This program puts B in it's own element as

<a>
      <avalue>a</avalue>
      <b>
        <bvalue>b</bvalue>
      </b>
    </a>
public class A
{
    public string avalue = "a";
    public B b = new B();
}

public class B
{
    public string bvalue = "b";
}

class Program
{
    static void Main(string[] args)
    {
        var a = new A();
        var xml = new XmlSerializer(a.GetType());
        xml.Serialize(new StreamWriter(@"c:\temp\tmp.xml"), a);
    }
}

PS: This must have been asked before, but I'm not sure what to search for. My google-fu turns up empty...

Edit:

And I'm hoping to avoid the "wrapper" solution if possible:

public class A
{
    public string avalue = "a";

    [XmlIgnore]
    public B b { get; set; }

    [XmlElement("bvalue")]
    public string bvalue
    {
        get { return b.bvalue; }
        set { b.bvalue = value;  }
    }
}

您需要设置B属性并用XMLAttribute对其进行标记。

Arseny's answer is correct, although it is a little ambiguous, so here is what needs to change:

public class B
{
      [XmlAttribute]
      public string bvalue = "b";
}

And that outputs:

<?xml version="1.0" encoding="utf-8"?>
<A>
  <avalue>a</avalue>
  <b bvalue="b" />
</A>

Hope that's what you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM