首页 > 解决方案 > 从大型 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)
    {
    }

标签: c#xmlinnertext

解决方案


感谢 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
    }
    }

为了清楚起见,有评论


推荐阅读