gpt4 book ai didi

c# - 如何在反序列化之前区分 XML 文件的类型?

转载 作者:数据小太阳 更新时间:2023-10-29 01:50:27 28 4
gpt4 key购买 nike

我正在将 MusicXML 文件加载到我的程序中。问题:有两种“方言”,timewisepartwise,它们具有不同的根节点(和不同的结构):

<?xml version="1.0" encoding='UTF-8' standalone='no' ?>
<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 2.0 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">
<score-partwise version="2.0">
<work>...</work>
...
</score-partwise>

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE score-timewise PUBLIC "-//Recordare//DTD MusicXML 2.0 Timewise//EN" "http://www.musicxml.org/dtds/timewise.dtd">
<score-timewise version="2.0">
<work>...</work>
...
</score-timewise>

到目前为止,我用于反序列化部分分数的代码是:

using (var fileStream = new FileStream(openFileDialog.FileName, FileMode.Open))
{
var xmlSerializer = new XmlSerializer(typeof(ScorePartwise));
var result = (ScorePartwise)xmlSerializer.Deserialize(fileStream);
}

区分这两种方言的最佳方法是什么?

最佳答案

这是一种使用 XDocument 来实现的方法解析文件,读取根元素以确定类型,并将其读入序列化程序。

var xdoc = XDocument.Load(filePath);
Type type;
if (xdoc.Root.Name.LocalName == "score-partwise")
type = typeof(ScorePartwise);
else if (xdoc.Root.Name.LocalName == "score-timewise")
type = typeof(ScoreTimewise);
else
throw new Exception();
var xmlSerializer = new XmlSerializer(type);
var result = xmlSerializer.Deserialize(xdoc.CreateReader());

关于c# - 如何在反序列化之前区分 XML 文件的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23663316/

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