2 回答
TA贡献1936条经验 获得超6个赞
如果您想要两个 XML 的单个类,请尝试此操作
string xmlText1 = @"<PARM KEY=""K1"" VALUE=""V1""/>";
string xmlText2 = @"<PARM><KEY>K2</KEY><VALUE>V2</VALUE></PARM>";
[XmlRoot(ElementName = "PARM")]
public class ParmInfo
{
[XmlAttribute("KEY")]
public string ParmAttrKey { get; set; }
[XmlAttribute("VALUE")]
public string ParmAttrVal { get; set; }
[XmlElement("KEY")]
public string ParmEleKey { get; set; }
[XmlElement("VALUE")]
public string ParmEleVal { get; set; }
public ParmInfo()
{
}
public ParmInfo(string inpParmEleKey, string inpParmEleVal, string inpParmAttrKey, string inpParmAttrVal)
{
ParmEleKey = inpParmEleKey;
ParmEleVal = inpParmEleVal;
ParmAttrKey = inpParmAttrKey;
ParmAttrVal = inpParmAttrVal;
}
}
这是我用来序列化的
string xmlText1 = @"<PARM KEY=""K1"" VALUE=""V1""/>";
string xmlText2 = @"<PARM><KEY>K2</KEY><VALUE>V2</VALUE></PARM>";
XmlSerializer serializer = new XmlSerializer(typeof(ParmInfo));
StringReader stringReader = new StringReader(xmlText1);
var xmlText1Serialized = (ParmInfo)serializer.Deserialize(stringReader);
stringReader = new StringReader(xmlText2);
var xmlText2Serialized = (ParmInfo)serializer.Deserialize(stringReader);
TA贡献1831条经验 获得超10个赞
这就是我最终完成的事情。我希望避免这种情况。但无论如何。
[Serializable]
[XmlRoot(ElementName = "PARM")]
public class ParmInfo
{
private string _ParmName;
private string _ParmVal;
private bool _UsingAttr = false;
[XmlElement("KEY", IsNullable = true)]
public string ParmName
{
get
{
return _ParmName;
}
set
{
if(!string.IsNullOrEmpty(value))
{
_ParmName = value;
_UsingAttr = false;
}
}
}
[XmlElement("VALUE", IsNullable = true)]
public string ParmVal
{
get
{
return _ParmVal;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_ParmVal = value;
}
}
}
[XmlAttribute("KEY")]
public string ParmNameAttr
{
get
{
return _ParmName;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_ParmName = value;
_UsingAttr = true;
}
}
}
[XmlAttribute("VALUE")]
public string ParmValueAttr
{
get
{
return _ParmVal;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_ParmVal = value;
}
}
}
public ParmInfo()
{
}
public ParmInfo(string inpParmName, string inpParmVal)
{
ParmName = inpParmName;
_ParmVal = inpParmVal;
}
}
- 2 回答
- 0 关注
- 159 浏览
添加回答
举报