查找特定节点的XML子节点并将其插入DataTable中

本文关键字:插入 DataTable 子节点 节点 XML 查找 | 更新日期: 2023-09-27 18:12:21

我有这个样式XML:

<Style Name="TextBox2" Type="TEXT">
        <Alignment>LEFT</Alignment>
        <BorderColor>blue</BorderColor>
        <BorderStyle>Solid</BorderStyle>
        <BackGroundColor>red</BackGroundColor>
        <Options>VISIBLE</Options>
        <TextColor>Black</TextColor>
        <TextSize>10</TextSize>
        <MaxCharacterLength>50</MaxCharacterLength>

我想写一个函数,使我能够搜索一个名称(例如Checkbox2),并返回我们对应的名称和子节点的值(align =Center, Bordercolor=red等)。我应该使用数据表还是数据集?如有任何建议,不胜感激

查找特定节点的XML子节点并将其插入DataTable中

试试这样只获取一个对象

            string xml =
            "<Root>" +
                "<Style Name='"TextBox2'" Type='"TEXT'">" +
                    "<Alignment>LEFT</Alignment>" +
                    "<BorderColor>blue</BorderColor>" +
                    "<BorderStyle>Solid</BorderStyle>" +
                    "<BackGroundColor>red</BackGroundColor>" +
                    "<Options>VISIBLE</Options>" +
                    "<TextColor>Black</TextColor>" +
                    "<TextSize>10</TextSize>" +
                    "<MaxCharacterLength>50</MaxCharacterLength>" +
                "</Style>" +
            "</Root>";
            XDocument doc = XDocument.Parse(xml);
            var style = doc.Descendants("Style").Where(x => (string)x.Attribute("Name") == "TextBox2").Select(x => new
            {
                type = (string)x.Attribute("Type"),
                alignment = (string)x.Element("Alignment"),
                borderColor = (string)x.Element("BorderColor"),
                borderStyle = (string)x.Element("BorderStyle"),
                background = (string)x.Element("BackGroundColor"),
                options = (string)x.Element("Options"),
                textColor = (string)x.Element("TextColor"),
                textSize = (string)x.Element("TextSize"),
                maxCharacters = (int)x.Element("MaxCharacterLength"),
            }).FirstOrDefault();