【问题标题】:filtering XML nodes containing a greater-than character in node text过滤节点文本中包含大于号字符的 XML 节点
【发布时间】:2023-03-02 22:52:02
【问题描述】:

我有一个来自 XML 文件的 LINQ 查询。我正在过滤掉某些具有空子节点的节点,但也想过滤包含非法字符的节点。

从下面的示例中,您可以看到我正在尝试过滤其中也包含大于号字符 < 的节点。 (参见 XML 示例中的 child3)

但是,这不起作用。我可以测试节点内的其他字符,例如*,但< 不起作用。

如何修改我的 LINQ 查询以检查节点内的大于字符 <

<Root>
   <Header>
        <total>123456</total>
    </Header>
    <Transactions>
      <Txn>
         <child1>BSmith</value1>
         <child2>Bob Smith</child2>
         <child3>Acme Company<</child3>
         <child4>Suite 3B</child4>
         <child5>1234 Main Street</child5>
      </Txn>
      ...
    </Transactions>
</Root>

var root = XElement.Parse(xmlText);                
var elementsThatCanBeEmpty = new HashSet<XName>
{
    XName.Get("child4")
};

var transactionList = from transactions in 
                      root.Elements(XName.Get("Transactions"))
                      .Elements().AsEnumerable()
                      where transactions.Elements().Any
                      (
                        el =>
                        (String.IsNullOrEmpty(el.Value) || el.Value.Contains("*")) &&
                        !elementsThatCanBeEmpty.Contains(el.Name)
                      )
                      select new 
                      { 
                         UserName = transactions.Element(XName.Get("child1")).Value
                      };

【问题讨论】:

  • 文件中的
  • 您发布的 XML 根本无效,因此您的代码的第一行应该引发异常,并且您不能将 LINQ to XML 与这样的“XML”一起使用。
  • @schroedingers-cat,既然你提到了,是的,这是非法的。第三方公司向我们发送了这个 xml 文件,我正在检查文件中的不一致和空节点。碰巧最终用户可以在字段中输入
  • 那么我建议第一阶段是在尝试使用 XML 工具之前验证 XML 是否有效。
  • @Nick,如果用户输入&amp;lt;,正确的做法是对其进行编码(如&amp;lt;),我认为任何 XML 库都会自动执行此操作。

标签: c# asp.net xml linq


【解决方案1】:

看看这个。这对您来说是一个很好的起点,您可以使用 WHERE 关键字来过滤您的 XML 数据

http://www.switchonthecode.com/tutorials/introduction-to-linq-simple-xml-parsing

【讨论】:

    猜你喜欢
    • 2014-11-17
    • 2020-08-28
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多