【发布时间】:2020-07-30 11:11:57
【问题描述】:
我的 XML 文件如下所示:
<device name="dev. 1" nodes="16" scenarios="20">
<package>Pack. 1</package>
<info>info...</info>
<picture>pic</picture>
<nodes>
<node no="1" name="OUT_1" type="source"/>
<node no="2" name="OUT_2" type="source"/>
<node no="3" name="OUT_3" type="source"/>
<node no="4" name="OUT_4" type="source"/>
</nodes>
<scenario name="scenario 1">
<zth m_node="1" d_node="1" model="table" points="190">
<data time="1" value="0.1"/>
<data time="2" value="2"/>
<data time="2" value="4"/>
</zth>
<zth m_node="1" d_node="2" model="table" points="190">
<data time="1" value="0.3"/>
<data time="2" value="4"/>
</zth>
</scenario>
<scenario name="scenario 2">
<zth m_node="1" d_node="1" model="table" points="190">
<data time="2" value="2"/>
<data time="1" value="0.3"/>
<data time="2" value="4"/>
</zth>
<zth m_node="1" d_node="2" model="table" points="190">
<data time="1" value="0.3"/>
<data time="2" value="4"/>
</zth>
</scenario>
</device>
我需要读取的数据是:
Element 场景中的属性名称在<data> 中,我需要将数据中的时间和值获取到数组中,但前提是d_node="2" 在<zth> 中。
这是我尝试过的:
public class Scenario {
public string name { get; set; }
public List<string> ZthList { get; set; }
}
public class Zth {
public string m_node { get; set; }
public string d_node { get; set; }
public string time { get; set; }
public string value { get; set; }
}
public class XMLReader
{
public void xmlReader()
{
string currentDir = Environment.CurrentDirectory;
//getting the directory
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + @"utils\XML\XMLFile1.xml")));
XDocument doc = XDocument.Load(Path.Combine(currentDir, @"..\..\" + @"utils\XML\XMLFile1.xml"));
var scenarios = (from s in doc.Root.Elements("scenario")
select new Scenario{
name = (string)s.Attribute("name"),
ZthList = s.Elements("zth")
.Select(r => new Zth
{
m_node = (string)r.Attribute("m_node"),
d_node = (string)r.Attribute("d_node"),
time = (string)r.Element("data").Attribute("time"),
value = (string)r.Element("data").Attribute("value"),
}).ToList()
}).ToList();
var zth_d_node = scenarios.Where(x => x.ZthList.Any(r => r.d_node == "1")).ToList();
var s_names = scenarios.Where(x => x.Element("").Value.Equals("name")).toList();
Console.WriteLine("List: ");
Console.WriteLine(String.Join(", ", scenarios));
}
}
我收到错误:Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<project1.utils.Zth>' to 'System.Collections.Generic.List<string>'
time 和 value 中的数据也是 double 类型,我将其更改为字符串,因为我遇到了类似的错误,但它仍然无法正常工作
【问题讨论】: