【问题标题】:How to get attributes from xml/scxml如何从 xml/scxml 获取属性
【发布时间】:2013-11-21 16:43:49
【问题描述】:

我正在尝试使用 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"));
}

【问题讨论】:

  • 抱歉,我没能弄清楚问题出在哪里。
  • @OndrejJanacek ,“IDeveloper”有一个很好的解决方案。只是为了让你知道。 =)
  • 谢谢,我很感激 :) 我不会来这个解决方案。

标签: c# xml linq xml-parsing linq-to-xml


【解决方案1】:

您的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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多