【问题标题】:LINQ to XML selection/updateLINQ to XML 选择/更新
【发布时间】:2011-09-10 18:30:17
【问题描述】:

如果我有以下 XML,我将如何使用 LINQ to XML 清除每个视频节点中的日期字段?我想这样做是为了在单元测试中进行比较。

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<main>
<videos>
    <video>
        <id>00000000-0000-0000-0000-000000000000</id>
        <title>Video Title</title>
        <videourl>http://sample.com</videourl>
        <thumbnail>http://sample.com</thumbnail>
        <dateCreated>2011-01-12T18:54:56.7318386-05:00</dateCreated>
        <dateModified>2011-02-12T18:54:56.7318386-05:00</dateModified>
        <Numbers>
            <Number>28</Number>
            <Number>78</Number>
        </Numbers>
    </video>
    <video>
        <id>00000000-0000-0000-0000-000000000000</id>
        <title>Video Title</title>
        <videourl>http://sample.com</videourl>
        <thumbnail>http://sample.com</thumbnail>
        <dateCreated>2011-01-12T18:54:56.7318386-05:00</dateCreated>
        <dateModified>2011-02-12T18:54:56.7318386-05:00</dateModified>
        <Numbers>
            <Number>28</Number>
            <Number>78</Number>
        </Numbers>
    </video>
</videos>

【问题讨论】:

  • 请重新格式化您的代码,我看不到 XML,只能看到纯文本。

标签: linq-to-xml


【解决方案1】:

如果你只是想清除节点的内容:

// Load the XML document
XDocument doc = ...;

// Select the date nodes
var query = doc.Descendants()
               .Where(e => e.Name.LocalName.StartsWith("date"));

// Clear the contents of each
foreach (var element in query)
{
    element.SetValue(String.Empty);
}

// Optionally write it back
doc.Save(...);

产量:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<main>
  <videos>
    <video>
      <id>00000000-0000-0000-0000-000000000000</id>
      <title>Video Title</title>
      <videourl>http://sample.com</videourl>
      <thumbnail>http://sample.com</thumbnail>
      <dateCreated></dateCreated>
      <dateModified></dateModified>
      <Numbers>
        <Number>28</Number>
        <Number>78</Number>
      </Numbers>
    </video>
    <video>
      <id>00000000-0000-0000-0000-000000000000</id>
      <title>Video Title</title>
      <videourl>http://sample.com</videourl>
      <thumbnail>http://sample.com</thumbnail>
      <dateCreated></dateCreated>
      <dateModified></dateModified>
      <Numbers>
        <Number>28</Number>
        <Number>78</Number>
      </Numbers>
    </video>
  </videos>
</main>

不幸的是,它会修改所有日期节点,无论它们在您的 XML 中的什么位置。我个人更喜欢在上面使用XPath 查询,如果给出的选项非常明确应该更新哪些节点。使用纯LINQ to XML 也可以做到这一点,但没有这个优雅。

var xpath = "/main/videos/video/*[starts-with(name(.),'date')]";
var query = doc.XPathSelectElements(xpath);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多