[英]How to get attributes from xml/scxml
我正在尝试使用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"));
}
编辑:以下代码也不起作用。 控制台警告null可能性(可抑制)。 什么都没有回来。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.