c# - 从大型 xml 文件中读取单个元素的内部文本
问题描述
我有一个已保存为字符串的大型单节点 .xml 文件。我想解析 .xml 文件以读取特定元素并输出内部文本。EG:我想读取 FrameNo 元素并将 BINGO 输出到消息框。所需的元素只会在 .xml 文档中出现一次。我更喜欢使用 XmlDocument。
我尝试了许多 C# .xml 示例,但无法获得输出。
xml文本是
<Aircraft z:Id="i1" xmlns="http://xxx.yyyyycontract.gov/2018/03/Boeing.xxxxxxxxxxxxxx.Airframe"
xmlns:i="http://www.xxxxxxx.com/2019/XMLSchema-instance"
xmlns:z="http://xxxxxxx.xxxxxxxxx.com/2005/01/Serialization/"><Timestamp i:nil="true"/>
<Uuid>00000000-0000-0000-0000-000000000000</Uuid><Comments i:nil="true"/><Facility>..........
依此类推到 .xml 的末尾
<FrameNo>BINGO</FrameNo><WDate i:nil="true"/></Aircraft>
这是我想要执行代码的代码部分。
private void buttonLoad_Click(object sender, EventArgs e)
{
}
解决方案
感谢 jdweng,我想分享最终代码供其他人使用。这将在下面的方法中起作用
private void buttonMaint_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Parse(xmlinputstr); // input string from memory or input file
XNamespace ns = doc.Root.GetDefaultNamespace();
string[] Frame = doc.Descendants(ns + "FrameNo").Select(x => (string)x).ToArray(); // selects element to read + trailing character of >
string frame = string.Join("", Frame); //converts from array to string
if (string.IsNullOrEmpty(frame)) // check for empty result
{
txtFrame.Text = "not found"; //outputs to textbox
}
else
{
txtFrame.Text = (frame); //outputs to textbox
}
}
为了清楚起见,有评论
推荐阅读
- angular - 无法在 Ubuntu 18.04 上安装 Angular cli
- maven - Jenkins阶段maven安装被跳过
- c# - 如何在 C# 中检查 yyyyMMddHHmmss 格式的字符串?
- c# - 使用 C# 将 SharePoint 库 XML 文档转换为 PDF 文档
- webpack - 添加 Bootstrap 后,Webpack Encore 平均编译时间从 160ms 下降到 270ms
- javascript - 状态正在更新,但图像未呈现
- r - 在一个语句中计算多个移动计算
- python - 如何对 200 个函数进行错误处理?
- java - SWT 文本中的上下文菜单的子菜单
- java - Linux 机器中用于堆使用所需的 jmap 命令的替代