【问题标题】:XML Name Cannot Begin with the "=" CharacterXML 名称不能以“=”字符开头
【发布时间】:2020-10-08 20:01:45
【问题描述】:

我已经阅读了 % 字符的similar post,但似乎其他问题可以在标题行中解决。是否有某些字符不允许在 XML 中使用,或者我是否需要以另一种方式格式化文档(在我的情况下,“=”字符在尝试用 C# 读取文档时给我带来了麻烦)?

Name cannot begin with the character ' ',也类似,但仍由标头固定。

XElement nodes = XElement.Load(filename);  

XML 的结构如下:

<?xml version="1.0" encoding="utf-8"?>
<offer>
  <data id="Salary">
    <ocrstring>which is equal to $60,000.00 if working 40 hours per week</ocrstring>
    <rule>.*(([+-]?\$[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}))</rule>
    <output></output>
  </data>
  <data id="Hours">
    <ocrstring></ocrstring>
    <rule>"(?<=working).*?(?=hours)"</rule>    <!-- Error Occurring Here -->
    <output>bob</output>
  </data>
  <data id="Location">
    <ocrstring></ocrstring>
    <rule>Regex2</rule>
    <output>LongWindingRoad222</output>
  </data>
</offer>

如何解析 XML 文档而不出现不能以字符开头“=”错误

【问题讨论】:

  • 我认为这实际上是前面的“小于”(&amp;lt;)字符的副作用,它表示元素的开始。将您的“小于”符号编码为&amp;lt;,看看是否有帮助。另外,请参阅此问答:What characters do I need to escape in XML documents?
  • 你从哪里得到这个 xml?问题必须在出现的地方解决。最初生成的 xml 无效。您需要修复它的创建方式。
  • 错误是由于小于号在字符串中(左尖括号)。括号在 XML 中为标记名称保留,当用于内部文本时必须是 <

标签: c# xml xml-parsing


【解决方案1】:

您需要对所有 &lt;rule&gt; 元素使用 CDATA 部分。

What does <![CDATA[]]> in XML mean?

XML

<?xml version="1.0" encoding="utf-8"?>
<offer>
    <data id="Salary">
        <ocrstring>which is equal to $60,000.00 if working 40 hours per week</ocrstring>
        <rule><![CDATA[.*(([+-]?\$[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}))]]></rule>
        <output></output>
    </data>
    <data id="Hours">
        <ocrstring></ocrstring>
        <rule><![CDATA["(?<=working).*?(?=hours)"]]></rule>
        <!-- Error Occurring Here -->
        <output>bob</output>
    </data>
    <data id="Location">
        <ocrstring></ocrstring>
        <rule>Regex2</rule>
        <output>LongWindingRoad222</output>
    </data>
</offer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多