相关疑难解决方法(0)

将对象序列化为XmlDocument

为了返回SoapException.Detailasmx Web服务的有用信息,我从WCF中获取了一个想法,并创建了一个包含所述有用信息的错误类.然后将该故障对象序列化为XmlNode抛出所需的对象SoapException.

我想知道我是否有最好的代码来创建XmlDocument- 这是我对它的看法:

var xmlDocument = new XmlDocument();
var serializer = new XmlSerializer(typeof(T));
using (var stream = new MemoryStream())
{
    serializer.Serialize(stream, theObjectContainingUsefulInformation);
    stream.Flush();
    stream.Seek(0, SeekOrigin.Begin);

    xmlDocument.Load(stream);
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

更新:我实际上最终执行了以下操作,因为除非您将XML包装在<detail>xml元素中,否则您将SoapHeaderException在客户端获得:

var serialiseToDocument = new XmlDocument();
var serializer = new XmlSerializer(typeof(T));
using (var stream = new MemoryStream())
{
    serializer.Serialize(stream, e.ExceptionContext);
    stream.Flush();
    stream.Seek(0, SeekOrigin.Begin);

    serialiseToDocument.Load(stream);
}

// Remove the xml declaration
serialiseToDocument.RemoveChild(serialiseToDocument.FirstChild);

// Memorise the node we want
var …
Run Code Online (Sandbox Code Playgroud)

c# xmldocument xml-serialization

14
推荐指数
1
解决办法
3万
查看次数

如何在不事先知道类型的情况下反序列化XML?

说我有几个这样的基本对象:

[Serializable]
public class Base
{

    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

[Serializable]
public class Sub: Base
{
    public List<string> Property3 { get; set; }

    public Sub():base()
    {
        Property3 = new List<string>();
    }        
}
Run Code Online (Sandbox Code Playgroud)

我像这样序列化它们:

Sub s = new Sub {Property1 = "subtest", Property2 = 1000};
s.Property3.Add("item 1");
s.Property3.Add("item 2");

XmlSerializer sFormater = new XmlSerializer(typeof(Sub));
using (FileStream fStream = new FileStream("SubData.xml", 
    FileMode.Create, FileAccess.Write, FileShare.None))
{
    sFormater.Serialize(fStream, s);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能反序化它们,以便我找回正确的课程?

就像在,我想要这样的东西

XmlSerializer …
Run Code Online (Sandbox Code Playgroud)

.net serialization xml-serialization

13
推荐指数
2
解决办法
1万
查看次数

标签 统计

xml-serialization ×2

.net ×1

c# ×1

serialization ×1

xmldocument ×1