我正在尝试使用LINQ表达式从scxml文件中的“状态”和“过渡”中获取属性。
这是scxml文件:
<?xml version="1.0" encoding="utf-8"?>
<scxml xmlns:musthave="http://musthave.com/scxml/1.0" version="1.0" initial="Start" xmlns="http://www.w3.org/2005/07/scxml">
<state id="abc" musthave:displaystate="abcd" musthave:attribute1="None" musthave:attribute2="None">
<transition attribute3="blabla" attribute4="blabla" xmlns=""/>
</state>
<state id="bla" musthave:displaystate="ababab" musthave:attribute2="View" musthave:attribute1="View"/>
</scxml>
这是我在做什么:
var scxml = XDocument.Load(@"c:\test_scmxl.scxml");
如果在控制台上打印,则显示:
<scxml xmlns:musthave="http://musthave.com/scxml/1.0" version="1.0" initial="Start" xmlns="http://www.w3.org/2005/07/scxml">
<state id="abc" musthave:displaystate="abcd" musthave:attribute1="None" musthave:attribute2="None">
<transition attribute3="blabla" attribute4="blabla" xmlns=""/>
</state>
<state id="bla" musthave:displaystate="ababab" musthave:attribute2="View" musthave:attribute1="View"/>
</scxml>
我试图像这样获得所有“状态”:
foreach (var s in scxml.Descendants("state"))
{
Console.WriteLine(s.FirstAttribute);
}
当我打印它以查看是否获得id =“ abc”时,在此示例中,它不返回任何内容。
虽然,如果我运行代码:
foreach (var xNode in scxml.Elements().Select(element => (from test in element.Nodes() select test)).SelectMany(a => a))
{
Console.WriteLine(xNode);
Console.WriteLine("\n\n\n");
}
它告诉我:
<state id="abc" musthave:displaystate="abcd" musthave:attribute1="None" musthave:attribute2="None" xmlns:musthave="http://musthave.com/scxml/1.0" xmlns="http://www.w3.org/2005/07/scxml">
<transition attribute3="blabla" attribute4="blabla" xmlns="" />
</state>
<state id="bla" musthave:displaystate="" musthave:attribute2="View" musthave:attribute1="View" xmlns:musthave="http://musthave.com/scxml/1.0"
xmlns="http://www.w3.org/2005/07/scxml" />
有什么想法吗?
注意:我已经阅读了许多文章,并尝试按照此处的建议进行操作,但是到目前为止似乎没有任何效果。
编辑:它没有任何属性,就像“第一个属性”。
foreach (var state in scxml.Descendants("state"))
{
Console.WriteLine(state.Attribute("id"));
}
编辑:以下代码也不起作用。控制台会警告可能的可能性(可抑制)。一无所获。
foreach (var state in scxml.Root.Descendants("state"))
{
Console.WriteLine(state.Attribute("id"));
}
scxml
标签中有一个名称空间,因此您需要将其与内部标签一起使用才能访问它们。这是您需要的代码:
XDocument xdoc = XDocument.Load(path_to_xml);
XNamespace ns = "http://www.w3.org/2005/07/scxml";
foreach (var state in xdoc.Descendants(ns + "state"))
{
Console.WriteLine(state.Attribute("id").Value);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句