gpt4 book ai didi

C# 使用 XmlReader 获取额外的空白值,但不使用 XmlDocument

转载 作者:行者123 更新时间:2023-12-05 06:38:30 25 4
gpt4 key购买 nike

我有一个情况我不太明白。阅读以下 XML 时:

<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Countries>
<Country>
<CountryCode>CN</CountryCode>
<CurrentStatus>Active</CurrentStatus>
</Country>
</Countries>

<Countries>
<Country>
<CountryCode>AU</CountryCode>
<CurrentStatus>Cancelled</CurrentStatus>
</Country>
<Country>
<CountryCode>CN</CountryCode>
<CurrentStatus>Cancelled</CurrentStatus>
</Country>
<Country>
<CountryCode>US</CountryCode>
<CurrentStatus>Active</CurrentStatus>
</Country>
</Countries>

<Countries xsi:nil="true" />
</Root>

使用以下代码:

//No whitespace
string xml = File.ReadAllText(fileInfo.FullName);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string json1 = JsonConvert.SerializeXmlNode(xmlDoc);

//With whitespace
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;

using (XmlReader reader = XmlReader.Create(fileInfo.FullName, settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
XmlNode node = doc.ReadNode(reader);
string json2 = JsonConvert.SerializeXmlNode(node);
}
}
}

我得到的 json 看起来像这样:

json1:

{"?xml":{"@version":"1.0","@encoding":"utf-8"},"Root":{"@xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","Countries":[{"Country":{"CountryCode":"CN","CurrentStatus":"Active"}},{"Country":[{"CountryCode":"AU","CurrentStatus":"Cancelled"},{"CountryCode":"CN","CurrentStatus":"Cancelled"},{"CountryCode":"JP","CurrentStatus":"Cancelled"},{"CountryCode":"SG","CurrentStatus":"Cancelled"},{"CountryCode":"US","CurrentStatus":"Active"}]},{"@xsi:nil":"true"}]}}

json2:

{"Root":{"@xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","#whitespace":["\n ","\n ","\n ","\n"],"Countries":[{"#whitespace":["\n ","\n "],"Country":{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"CN","CurrentStatus":"Active"}},{"#whitespace":["\n
","\n ","\n ","\n ","\n ","\n "],"Country":[{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"AU","CurrentStatus":"Cancelled"},{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"CN","CurrentStatus":"Cancelled"},{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"JP","CurrentStatus":"Cancelled"},{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"SG","CurrentStatus":"Cancelled"},{"#whitespace":["\n ","\n ","\n
"],"CountryCode":"US","CurrentStatus":"Active"}]},{"@xsi:nil":"true"}]}}

为什么 XmlReader 会生成空格,而 XmlDocument 不会?考虑到 XML 值,我认为它们不应该存在。

最佳答案

解决方法:

settings.IgnoreWhitespace = true;

感谢@HenkHolterman 和@finrod。

关于C# 使用 XmlReader 获取额外的空白值,但不使用 XmlDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45961270/

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