3

当我使用 JsonConvert.SerializeXNode 或 JsonConvert.SerializeXmlNode 解析 XML 时,以下代码

XElement person = XElement.Parse(@"
  <person>
    <name>Palle</name>
    <member>true</member>
  </person>");

string json = JsonConvert.SerializeXNode(person);

给我这个 json 结果:

{"person":{"name":"Palle","member":"true"}}

这里成员输入为字符串,我希望将其输入为布尔值。我可以在 XML 中添加类型提示(如<member type="xsd:boolean">true</member>)并让解析器对此进行处理吗?

我想得到这个结果:

{"person":{"name":"Palle","member":true}}
4

1 回答 1

0

也许是这样的:

[TestFixture]
public class Class1
{
    [Test]
    public void DateTimeTest()
    {
        string xml = @"<person><name>Palle</name><member>true</member></person>";
        person person = xml.Deserialize<person>();
        var serializeXNode = JsonConvert.SerializeObject(person);
    }
}

public class person
{
    public string name { get; set; }
    public bool member { get; set; }
}

public static class Extension
{
    public static T Deserialize<T>(this string xml)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        using (var stringReader = new StringReader(xml))
        {
            using (var xmlReader = XmlReader.Create(stringReader))
            {
                return (T) xmlSerializer.Deserialize(xmlReader);
            }
        }
    }
}
于 2012-10-21T18:05:08.410 回答