【问题标题】:How to select single XML node value fastest如何最快地选择单个 XML 节点值
【发布时间】:2014-03-07 23:47:51
【问题描述】:

我有以下 xml

<?xml version='1.0'?>
<test>
    <exam paper="math" section="third" value="dull">
        <place>college</place> 
    </exam> 
</test>

我想获得“部分”的值并以最佳性能放置“标签”。我应该使用 linq 还是 xmldatareader?也请分享代码

【问题讨论】:

  • xml - college
  • 您的 XML 无效。 exam 元素未关闭。
  • college 现在使用更正的 xml
  • @user1607035:您可以编辑答案而不是添加 cmets。
  • 我在你的问题@StriplingWarrior ...而不是使用最佳性能这个词我应该使用“比vb代码更好”...我的道歉

标签: xml linq datareader


【解决方案1】:

XmlDataReader 可能比 LINQ to XML 更快,但 LINQ to XML 可能更容易编写和维护。

我能够在 0.1 秒多的时间内运行以下代码一万 (10,000) 次:您需要比这更好的性能吗?

var doc = XDocument.Parse(
@"<?xml version=""1.0""?>
<test>
    <exam paper=""math"" section=""third"" value=""dull"">
        <place>college</place>
    </exam>
</test>");
var info = 
    (from test in doc.Elements("test")
    from exam in test.Elements("exam")
    select new{
        section = exam.Attribute("section").Value,
        place = exam.Element("place").Value
    })
    .ToList();

【讨论】:

  • 太棒了 StriplingWarrior,当我在按钮提交事件上调用它时出现以下错误,我已经添加了命名空间 system.xml.linq。错误在以下代码中突出显示 - 文档。 Elements("test") 找不到源类型“System.Collections.Generic.IEnumerable”的查询模式的实现。未找到“SelectMany”。您是否缺少“System.Linq”的引用或使用指令?
  • @user1607035:嗯...你是否缺少“System.Linq”的 using 指令?
  • 感谢 Striplingwarrior,实际上我已经引用了它,所以无法真正找出问题所在..但我使用 XMLNode 基本上使用以下命令通过节点引用 - sec= node.Attributes.GetNamedItem("section ").InnerText; place= node.FirstChild.InnerText;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多