我正在尝试反序列化由不同软件创建的文件。我似乎无法弄清楚元素名称具有 2 个属性并且本身具有值的部分。
任何帮助将不胜感激:
public class Channel
{
[XmlAttribute("channelNumber")]
public string channelNumber;
[XmlAttribute("status")]
public string status;
[XmlAttribute("type")]
public string type;
[XmlAttribute("ca")]
public string ca;
[XmlAttribute("shortName")]
public string shortName;
[XmlAttribute("outOfBand")]
public string outOfBand;
//[XmlElement]
//[XmlAnyElement("Name")]
//[XmlAnyElement]
[XmlElement("Name")]
public NameClass Name;
}
//[XmlRoot(ElementName = "Name")]
public class NameClass
{
//[XmlElement(Order = 1)]
//[XmlAttribute]
[XmlAttribute("lang")]
public string lang { get; set; }
//[XmlIgnore]
//[XmlElement(Order = 2)]
//[XmlAttribute("xmlns")]
//[XmlAttribute]
//public string xmlns;
//[XmlElement("Name")]
[XmlText]
public string Value { get; set; }
}
我留下了我尝试过的所有东西……XML文件的部分如下:
<Channel channelNumber="1" status="active" type="dt" ca="false" shortName="CH" outOfBand="true">
<Name lang="eng" xmlns="http://www.atsc.org/XMLSchemas/pmcp/2007/3.1">CH</Name>
</Channel>
<ScheduleName>2020-05-06 CH Log</ScheduleName>
我无法阅读的部分是从名称“CH”和名称属性(“lang”和“xmlns”)中获取值,它们总是为空?
最佳答案
更改属性
[XmlElement("Name")]
public NameClass Name;
到
[XmlElement("Name", Namespace = "http://www.atsc.org/XMLSchemas/pmcp/2007/3.1")]
public NameClass Name;
您的
<Name>
元素是通过使用属性 xmlns=""
在选定的命名空间中定义的。 .您必须指定您也期望这样的元素。检查以下源代码:
public class Test
{
public class Channel
{
[XmlElement("Name", Namespace = "http://www.atsc.org/XMLSchemas/pmcp/2007/3.1")]
public NameClass Name;
}
public class NameClass
{
[XmlText]
public string Value { get; set; }
}
public static void Main(string[] args) {
string xmlContent = "<Channel channelNumber=\"1\" status=\"active\" type=\"dt\" ca=\"false\" shortName=\"CH\" outOfBand=\"true\">\n"+
" <Name lang=\"eng\" xmlns=\"http://www.atsc.org/XMLSchemas/pmcp/2007/3.1\">CH</Name>\n"+
"</Channel>";
Console.WriteLine("XML Content:");
Console.WriteLine(xmlContent);
XmlSerializer serializer = new XmlSerializer(typeof(Channel));
using (TextReader reader = new StringReader(xmlContent))
{
Channel result = (Channel) serializer.Deserialize(reader);
Console.WriteLine(result);
Console.WriteLine(result.Name);
Console.WriteLine(result.Name.Value);
}
}
}
这将生成以下输出:
XML Content:
<Channel channelNumber="1" status="active" type="dt" ca="false" shortName="CH" outOfBand="true">
<Name lang="eng" xmlns="http://www.atsc.org/XMLSchemas/pmcp/2007/3.1">CH</Name>
</Channel>
Test+Channel
Test+NameClass
CH
关于c# - 使用 C# 反序列化 XML 文件,其中元素具有属性和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61690000/