gpt4 book ai didi

c# - 在 XmlTextReader 对象中读取 'fake' xml 文档(xml 片段)

转载 作者:数据小太阳 更新时间:2023-10-29 02:54:04 28 4
gpt4 key购买 nike

[案例]我收到了一堆“xml 文件”,其中包含关于其中大量文档的元数据。至少,那是我的要求。我在没有根元素的“xml 文件”中收到的内容,它们的结构类似于这样(我遗漏了一堆元素):

<folder name = "abc"></folder>
<folder name = "abc/def">
<document name = "ghi1">
</document>
<document name = "ghi2">
</document>
</folder>

[问题]当我尝试读取 XmlTextReader 对象中的文件时,它无法告诉我没有根元素。

[当前解决方法]当然,我可以将文件作为流读取,附加 < xmlroot> 和 并将流写入新文件并在 XmlTextReader 中读取该文件。这正是我现在正在做的,但我不想“篡改”原始数据。

[请求的解决方案]我知道我应该为此使用 XmlTextReader 和 DocumentFragment 选项。但是,这会产生编译时错误:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: XmlNodeType DocumentFragment is not supported for partial content parsing. Line 1, position 1.

[错误代码]

using System.Diagnostics;
using System.Xml;

namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
string file = @"C:\test.txt";
XmlTextReader tr = new XmlTextReader(file, XmlNodeType.DocumentFragment, null);
while(tr.Read())
Debug.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
}
}
}

最佳答案

这个有效:

using System.Diagnostics;
using System.Xml;

namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
string file = @"C:\test.txt";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(file, settings))
{
while (reader.Read())
Debug.WriteLine("NodeType: {0} NodeName: {1}", reader.NodeType, reader.Name);
}
}
}
}

关于c# - 在 XmlTextReader 对象中读取 'fake' xml 文档(xml 片段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038663/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com