C# 将序列化对象与现有xml文档组合并返回它?

C# 将序列化对象与现有xml文档组合并返回它?,c#,web-services,xml-serialization,streamreader,C#,Web Services,Xml Serialization,Streamreader,我试图找出如何将序列化对象与现有xml文档相结合,并将其作为Web服务返回 谢谢你的帮助 示例代码: [WebMethod] public string GetApple() { Apples apples = Report.GetReport(); // this returns: // <Apples xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h

我试图找出如何将序列化对象与现有xml文档相结合,并将其作为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;
}
[WebMethod]
公共字符串GetApple()
{
Apples=Report.GetReport();
//这将返回:
//  
//Smtih
//  11
//  111
//红色的
//  
字符串TemplatePath=Server.MapPath(“~/Template.xml”);
//这是:
// 
// 
//  
//    
//      
//        
//      
//    
//  
// 
//将TemplatePath读入内存流
//查找节点:
// 
//将Report.GetReport()的序列化输出放在
返回完整报告;
}

您可以序列化不带命名空间和根的对象,然后将其合并


我现在没有时间讲完整的示例,但请看一下方法

其思想是在文档中获得一个指向要添加数据的
XPathNavigator
实例,然后使用
AppendChild
方法生成一个
XmlWriter
。使用该
XmlWriter
作为
XmlSerializer.Serialize
的参数


然后,您可以使用
xmlement
类型作为
WebMethod

的返回类型,从web服务返回整个
XmlDocument.DocumentElement
,对于我的情况,这起到了作用:

[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
} }
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
//要允许使用ASP.NET AJAX从脚本调用此Web服务,请取消注释以下行。
//[System.Web.Script.Services.ScriptService]
公共类WebService:System.Web.Services.WebService{
公共Web服务()
{
//如果使用设计的组件,请取消注释以下行
//初始化组件();
}
[网络方法]
公共XML文档GetApple()
{
Apples=Report.GetReport();
//这将返回:
//  
//Smtih
//  11
//  111
//红色的
//  
//系列化
string serializedXML=SerializeObject(苹果);
字符串TemplatePath=Server.MapPath(“~/Template.xml”);
//这是:
// 
// 
//  
//    
//      
//        
//      
//    
//  
// 
//将TemplatePath读入内存流
//查找节点:
// 
//将Report.GetReport()的序列化输出放在
XmlDocument xdoc=新的XmlDocument();
xdoc.Load(模板路径);
XmlNodeList datagoesher=xdoc.GetElementsByTagName(“DATA-GOES-HERE”);
if(datagoesher!=null&&datagoesher.Count>0)
DataGoesher[0]。InnerXml=serializedXML;
返回xdoc;
}
/// 
///将Unicode值(UTF-8编码)的字节数组转换为完整字符串。
/// 
///要转换为字符串的Unicode字节数组
///从Unicode字节数组转换的字符串
专用字符串UTF8ByteArrayToString(字节[]个字符)
{
UTF8Encoding=新的UTF8Encoding();
String constructedString=encoding.GetString(字符);
返回(构造字符串);
}
/// 
///将字符串转换为UTF8字节数组,并用于反序列化
/// 
/// 
/// 
专用字节[]StringToUTF8ByteArray(字符串pXmlString)
{
UTF8Encoding=新的UTF8Encoding();
Byte[]byteArray=encoding.GetBytes(pXmlString);
乘火车返回;
}
/// 
///方法将自定义对象转换为XML字符串
/// 
///要序列化为XML的对象
///XML字符串
公共字符串序列化对象(对象POObject)
{
尝试
{
//为输出创建我们自己的名称空间
XmlSerializerNamespaces ns=新的XmlSerializerNamespaces();
//添加空命名空间和空值
加上(“,”);
字符串XmlizedString=null;
MemoryStream MemoryStream=新的MemoryStream();
XmlSerializer xs=新的XmlSerializer(typeof(Apples));
XmlTextWriter XmlTextWriter=新的XmlTextWritePerformattedNodeClarasion(memoryStream,Encoding.UTF8);
序列化(xmlTextWriter、POObject、ns);
memoryStream=(memoryStream)xmlTextWriter.BaseStream;
XmlizedString=UTF8ByteArrayToString(memoryStream.ToArray());
返回XmlizedString.Trim();
}
捕获(例外e)
{
系统控制台写入线(e);
返回null;
}
}
公共类XmlTextWritePerformattedNodeClarition:System.Xml.XmlTextWriter
{
公共XmlTextWritePerformattedNodeClarasion(流w,编码)
:base(w,编码)
{
格式化=System.Xml.Formatting.Indented;
}
public override void WriteStartDocument(){}//suppress
} }
来自webserivce的回应是:

<?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>

Smtih
11
111
红色

hello,实际上它不应该是字符串,而应该是xml/序列化消息的字符串。我只是不知道该怎么做。换了答案,把问题弄错了,对不起,迟到了,累了为什么要在没有名称空间的情况下序列化?如果XML有一个名称空间,而您没有包含它,那么您就生成了无效的XML。