gpt4 book ai didi

c# - 将部分xml反序列化为字符串

转载 作者:行者123 更新时间:2023-11-30 20:46:44 25 4
gpt4 key购买 nike

是否可以反序列化以下 XML:

<MyObject><Test>Hi hello</Test><Something><Else><With><SubItems count='5'>hello world</SubItems></With></Else></Something></MyObject>

进入这个对象:

public class MyObject {
public string Test { get; set; }
public string Something { get; set; }
}

这是预期的输出(目前失败,出现 XmlException:意外的节点类型元素。ReadElementString 方法只能在内容简单或为空的元素上调用。第 1 行,位置 50。)

[TestMethod]
public void TestDeserialization()
{
var s = "<MyObject><Test>Hi hello</Test><Something><Else><With><SubItems count='5'>hello world</SubItems></With></Else></Something></MyObject>";

var o = s.DeSerialize<MyObject>();
Assert.AreEqual("Hi hello", o.Test);
Assert.AreEqual("<Else><With><SubItems count='5'>hello world</SubItems></With></Else>", o.Something);
}

public static class Xml
{
public static T DeSerialize<T>(this string xml) where T : new()
{
if (String.IsNullOrEmpty(xml))
{
return new T();
}
var xmlSer = new XmlSerializer(typeof(T));
using (var stream = new StringReader(xml))
return (T)xmlSer.Deserialize(stream);
}
}

最佳答案

一个选项可能是实现 IXmlSerializable所以你手动将内部 Xml 读入 Something 属性:

public class MyObject: IXmlSerializable 
{
public string Test { get; set; }
public string Something { get; set; }

public System.Xml.Schema.XmlSchema GetSchema() { return null; }

public void ReadXml(System.Xml.XmlReader reader)
{
if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyObject")
{
Test = reader["Test"];
if (reader.ReadToDescendant("Something"))
{
Something = reader.ReadInnerXml();
}
}
}

public void WriteXml(System.Xml.XmlWriter writer)
{
throw new NotImplementedException();
}
}

public static class Program
{
public static void Main()
{
var myObjectXmlString = "<MyObject><Test>Hi hello</Test><Something><Else><With><SubItems count='5'>hello world</SubItems></With></Else></Something></MyObject>";
var myObject =(MyObject) new XmlSerializer(typeof(MyObject)).Deserialize(new StringReader(myObjectXmlString));
Console.WriteLine(myObject.Something);
}
}

另一种选择是将 Something 转换为 XmlElement 类型的属性,这样内部随机的 Xml 片段将被序列化为 Xml 而不是字符串(您仍然可以检索通过获取其 OuterXml 将其作为字符串):

public class MyOtherObject 
{
public string Test { get; set; }
public XmlElement Something { get; set; }
public string SomethingString
{
get { return Something.OuterXml; }
}
}

public static class Program
{
public static void Main()
{
var otherObjectXmlString = "<MyOtherObject><Test>Hi hello</Test><Something><Else><With><SubItems count='5'>hello world</SubItems></With></Else></Something></MyOtherObject>";
var otherObject =(MyOtherObject) new XmlSerializer(typeof(MyOtherObject)).Deserialize(new StringReader(otherObjectXmlString));
Console.WriteLine(otherObject.SomethingString);
}
}

我创建了 this fiddle所以你可以试试看。

关于c# - 将部分xml反序列化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26525403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com