将序列化对象与现有xml doc组合并返回它?

时间:2010-07-06 20:44:03

标签: c# web-services xml-serialization streamreader

我正在努力想要将序列化对象与现有的xml doc结合起来并将其作为Web服务返回。

先谢谢你的帮助。

示例代码:

[WebMethod]
    public string GetApple()
    {

    Apples apples = Report.GetReport();
    //  this returns:
        //  <Apples xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
        //  <Name>Smtih</Name>
        //  <Size>11</Size>
        //  <Weight>111</Weight>
        //  <Color>Red</Color>
        //  </Apples>

    string TemplatePath = Server.MapPath("~/Template.xml");
        // this is:
        // <?xml version="1.0" encoding="utf-8" ?>
        // <applereport>
        //  <moretags>
        //    <july>
        //      <report>
        //        <DATA-GOES-HERE></DATA-GOES-HERE>
        //      </report>
        //    </july>
        //  </moretags>
        // </applereport>

        // Read TemplatePath into a memory stream
        // find the node: <DATA-GOES-HERE></DATA-GOES-HERE>
        // 
        // put serialixed output of Report.GetReport() where <DATA-GOES-HERE></DATA-GOES-HERE> is

        return FullReport;
}

3 个答案:

答案 0 :(得分:0)

您可以在没有命名空间和根的情况下序列化对象,然后将其合并。

Serializing without the namespace

答案 1 :(得分:0)

我现在没有时间查看完整示例,但请查看XPathNavigator.AppendChild方法。

我们的想法是将一个XPathNavigator实例指向您要添加数据的文档,然后使用AppendChild方法生成XmlWriter。使用XmlWriter作为XmlSerializer.Serialize的参数。

然后,您可以使用XmlDocument.DocumentElement类型作为XmlElement的返回类型,从Web服务返回整个WebMethod

答案 2 :(得分:0)

对于我的情况,这有效:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService()
{

    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
}

[WebMethod]
public XmlDocument GetApple()
{

    Apples apples = Report.GetReport();
    //  this returns:
    //  <Apples xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
    //  <Name>Smtih</Name>
    //  <Size>11</Size>
    //  <Weight>111</Weight>
    //  <Color>Red</Color>
    //  </Apples>

    // Serialization

    string serializedXML = SerializeObject(apples);



    string TemplatePath = Server.MapPath("~/Template.xml");
    // this is:
    // <?xml version="1.0" encoding="utf-8" ?>
    // <applereport>
    //  <moretags>
    //    <july>
    //      <report>
    //        <DATA-GOES-HERE></DATA-GOES-HERE>
    //      </report>
    //    </july>
    //  </moretags>
    // </applereport>


    // Read TemplatePath into a memory stream
    // find the node: <DATA-GOES-HERE></DATA-GOES-HERE>
    // 
    // put serialixed output of Report.GetReport() where <DATA-GOES-HERE></DATA-GOES-HERE> is
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(TemplatePath);
    XmlNodeList datagoeshere = xdoc.GetElementsByTagName("DATA-GOES-HERE");
    if (datagoeshere != null && datagoeshere.Count > 0)
        datagoeshere[0].InnerXml = serializedXML;


    return xdoc;
}
/// <summary>
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
/// </summary>
/// <param name="characters">Unicode Byte Array to be converted to String</param>
/// <returns>String converted from Unicode Byte Array</returns>
private String UTF8ByteArrayToString(Byte[] characters)
{
    UTF8Encoding encoding = new UTF8Encoding();
    String constructedString = encoding.GetString(characters);
    return (constructedString);
}

/// <summary>
/// Converts the String to UTF8 Byte array and is used in De serialization
/// </summary>
/// <param name="pXmlString"></param>
/// <returns></returns>
private Byte[] StringToUTF8ByteArray(String pXmlString)
{
    UTF8Encoding encoding = new UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(pXmlString);
    return byteArray;
}

/// <summary>
/// Method to convert a custom Object to XML string
/// </summary>
/// <param name="pObject">Object that is to be serialized to XML</param>
/// <returns>XML string</returns>
public String SerializeObject(Object pObject)
{
    try
    {
        //Create our own namespaces for the output
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

        //Add an empty namespace and empty value
        ns.Add("", "");


        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(Apples));
        XmlTextWriter xmlTextWriter = new XmlTextWriterFormattedNoDeclaration(memoryStream, Encoding.UTF8);

        xs.Serialize(xmlTextWriter, pObject, ns);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString.Trim();
    }
    catch (Exception e)
    {
        System.Console.WriteLine(e);
        return null;
    }
}

public class XmlTextWriterFormattedNoDeclaration : System.Xml.XmlTextWriter
{
    public XmlTextWriterFormattedNoDeclaration(Stream w, Encoding encoding)
        : base(w, encoding)
    {
        Formatting = System.Xml.Formatting.Indented;
    }

    public override void WriteStartDocument() { } // suppress
} }

并且来自Web服务的响应是:

<?xml version="1.0" encoding="utf-8"?>
<applereport>
  <moretags>
    <july>
      <report>
        <DATA-GOES-HERE>
          <Apples>
  <Name>Smtih</Name>
  <Size>11</Size>

  <Weight>111</Weight>
  <Color>Red</Color>
</Apples>
        </DATA-GOES-HERE>
      </report>
    </july>
  </moretags>
</applereport>