所以我试图像这样读取XML字符串
SaveGrammar[x].Item7 = "<condition><expression value=\"(not empty($20)) and ($20 = '1' or $20 = '2')\" /></condition><string-validity regexp=\".*\" domain=\"all-values\" />"
使用此方法
XElement validation = XElement.Parse(SaveGrammar[x].Item7);
问题是它会抛出下面的错误。
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: There are multiple root elements. Line 1, position 93
我知道我可以用
阅读XmlDocumentFragment validity = docXML.CreateDocumentFragment();
validity.InnerXml = SaveGrammar[x].Item7;
但是我不能用DOM做我需要的东西我需要使用LINQ。任何想法如何解决这个小问题?
答案 0 :(得分:0)
尝试,
string xml = "<root>" + SaveGrammar[x].Item7 + "</root>";
然后,
XElement validation = XElement.Parse(xml);
错误表明您有多个根元素。由于xml文件只能有一个根元素,所以使用上面的元素创建自己的元素,并在解析之前将多元素粘贴到其中。
答案 1 :(得分:0)
您的Xml内容有两个根:
<!-- root1 -->
<condition>
<expression value=\"(not empty($20)) and ($20 = '1' or $20 = '2')\" />
</condition>
<!-- root2 -->
<string-validity regexp=\".*\" domain=\"all-values\" />"
格式正确的xml文件应只包含一个根。就这样:
<root1>
<child1>
<subchild1>.....</subchild1>
</child1>
</root1>
这可以很容易地通过添加'parentroot'添加到内容中,使2个根嵌套在新的parentroot之下
<parnetroot>
<!-- root1 -->
<condition>
<expression value=\"(not empty($20)) and ($20 = '1' or $20 = '2')\" />
</condition>
<!-- root2 -->
<string-validity regexp=\".*\" domain=\"all-values\" />"
</parnetroot>