由于MediaInfo v17切换到XSD验证的XML,我尝试使用xsd.exe生成C#代码以反序列化MediaInfo XML文件。
https://mediaarea.net/MediaInfo/ChangeLog
Version 17.10, 2017-11-02
+ New MediaInfo XML output, with XSD, more suitable for automatic parsing. Use Option("Inform", "OLDXML") for keeping previous behavior
XSD工具:https://docs.microsoft.com/en-us/dotnet/standard/serialization/xml-schema-definition-tool-xsd-exe
MediaInfo XSD文件:https://mediaarea.net/mediainfo/mediainfo_2_0.xsd
创建C#绑定(在Visual Studio 2017预览版中):
xsd.exe /c /namespace:MediaInfoXml /language:CS mediainfo_2_0.xsd
生成的C#文件包含跟踪属性,代码段:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="https://mediaarea.net/mediainfo")]
public partial class trackType {
private object[] itemsField;
private ItemsChoiceType[] itemsElementNameField;
private extraType extraField;
private string typeField;
private string typeorderField;
public trackType() {
this.typeorderField = "1";
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Accompaniment", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("ActiveFormatDescription", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("Actor", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("Actor_Character", typeof(string))]
我从字符串中读取XML,然后找到track,snippet:
static public MediaInfoXml.mediainfoType FromXml(string xml)
{
XmlSerializer xmlserializer = new XmlSerializer(typeof(MediaInfoXml.mediainfoType));
TextReader textreader = new StringReader(xml);
return xmlserializer.Deserialize(textreader) as MediaInfoXml.mediainfoType;
}
...
MediaInfoXml.mediainfoType xmlinfo = MediaInfoTool.FromXml(xml);
MediaInfoXml.mediaType xmlmedia = xmlinfo.Items.First() as MediaInfoXml.mediaType;
foreach (MediaInfoXml.trackType track in xmlmedia.track)
{
if (track.type.Equals("Video", StringComparison.OrdinalIgnoreCase))
{
var attrib = track.Items[0];
var attrname = track.ItemsElementName[0];
// [System.Xml.Serialization.XmlElementAttribute("Language", typeof(string))]
// --> string language = track.Language; <--
}
}
属性值显示在Items []数组中,属性值显示在ItemsElementName []数组中的同一数组索引处。
如何直接按名称访问属性?