尝试使用XElement和LINQ将XML加载到类对象中
本文关键字:加载 XML 对象 LINQ XElement | 更新日期: 2023-09-27 18:06:01
我有以下XML
<Workflow Name="Workflow1">
<Parameter Name="Parameter1">Value1</Parameter>
<Parameter Name="Parameter2">Value2</Parameter>
<Environment Name="Environment1" Type="Typ1">
<DataCenter Name="DC1" DeployEnvironmentName="blah"/>
</Environment>
<Environment Name="Environment2" Type="Typ2">
<DataCenter Name="DC2" DeployEnvironmentName="blah"/>
</Environment>
我正在尝试将此XML读取为以下对象
class Workflow
{
public string Name { get; set; }
public IEnumerable<Parameter> Parameters { get; set; }
public IEnumerable<Environment> Environments { get; set; }
}
class Environment
{
public string Name { get; set; }
public EnvironmentType Type { get; set; }
public IEnumerable<DataCenter> DataCenters { get; set; }
}
class Parameter
{
public string Name { get; set; }
public string Value { get; set; }
}
class DataCenter
{
public string Name { get; set; }
public string DeployEnvironmentName { get; set; }
}
使用以下表达式
var root = XElement.Load(filePath);
var workflows =
root.Elements("Workflow")
.Select(
e =>
new Workflow
{
Name = e.Attribute("Name").Value,
Parameters = e.Elements("Parameter")
.Select(p =>
new Parameter { Name = p.Attribute("Name").Value, Value = p.Value }),
Environments = e.Elements("Environment").Select(
p =>
new Environment
{
Name = p.Attribute("Name").Value,
Type = (EnvironmentType)Enum.Parse(typeof
(EnvironmentType), p.Attribute("Type").Value, true),
DataCenters = p.Elements("DataCenter").Select(
dc => new DataCenter {
Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute
("DeployEnvironmentName").Value })
});
});
我一直得到一个语法错误。由于某种原因,它似乎不喜欢这些嵌套表达式。有人知道哪里出了问题或者知道更好的方法吗?提前感谢
你需要去掉这个分号
Name = p.Attribute("Name").Value,
Type = (EnvironmentType)Enum.Parse(typeof
(EnvironmentType), p.Attribute("Type").Value, true),
DataCenters = p.Elements("DataCenter").Select(
dc => new DataCenter {
Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute
("DeployEnvironmentName").Value })
});
^^^
});
你不应该在对象初始化式中使用分号,你应该用逗号分隔属性
您的XML文件似乎坏了。Workflow
标签从未关闭。