简体   繁体   中英

Can I serialize Xml for an MVC Web API without an object type?

So I'm writing my first mvc page, and I'm trying to write a series of routes to allow a reporting system to create simple reports. The xml is small, here is an example:

 <xml><root><item><value>23</value></item></root>

I tried this:

        using (StringWriter xmlStringWriter = new StringWriter())
        {
            using (XmlWriter xmlWriter =  XmlWriter.Create(xmlStringWriter))
            {

                  XmlWriter.WriteStartElement("root")
                  ...
            }
            return xmlStringWriter.ToString();
        }

but this obviously returns a string and is not interpreted as xml by the browser. I also know* that if you return an object that is serializable then the browser knows to interpret that as xml or json. So I tried defining a set of objects to hold each other in the way the xml is nested:

[Serializable]
public class XmlReportRoot
{
    [System.Xml.Serialization.XmlAttribute("root")]
    public List<XmlReportItem> item { get; set; }

}

[Serializable]
public class XmlReportItem
{
    [System.Xml.Serialization.XmlAttribute("item")]
    public XmlReportValue value { get; set; }

}

[Serializable]
public class XmlReportValue
{
    [System.Xml.Serialization.XmlAttribute("value")]
    public string count { get; set; }
}

and: XmlReportRoot xmlRoot = new XmlReportRoot();

        XmlReportItem xmlItem = new XmlReportItem();
        List<XmlReportItem> itemList = new List<XmlReportItem>();

        itemList.Add(xmlItem);

        XmlReportValue xmlValue = new XmlReportValue();
        xmlValue.count = newCustomers.ToString();

        xmlItem.value = xmlValue;

        xmlRoot.item = itemList;

        XmlSerializer xmlSer = new XmlSerializer(typeof(XmlReportRoot));
        xmlSer.Serialize(xmlRoot);  //this line doesn't work

but this just feels wrong, and I couldn't quite get the serialization to work without worrying about a file stream, which I would rather do.

So I guess I was trying to find a way to do something like XmlWriter but be able to serialize that without an object type and return that, instead of having to worry about custom serializable objects types.

使用XmlWriter.Create(Response.OutputStream)Response.ContentType = "application/xml"

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