我正在尝试使用LINQ表达式从scxml文件中的"state“和"transition”获取属性。
以下是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"));
}编辑:下面的代码也不起作用。Console警告空的可能性(可抑制的)。什么都不回。
foreach (var state in scxml.Root.Descendants("state"))
{
Console.WriteLine(state.Attribute("id"));
}发布于 2013-11-11 03:13:00
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);
}https://stackoverflow.com/questions/19879965
复制相似问题