简体   繁体   English

使用LINQ C#获取节点值xml

[英]Get node value xml with LINQ c#

I can't get the value of this XML node. 我无法获得此XML节点的值。

I need to get the <LimitValue> value and give the user the possibility to change it. 我需要获取<LimitValue>值,并为用户提供更改它的可能性。

I have already tried this solution, but it doesn't work: 我已经尝试过此解决方案,但是它不起作用:

namefile = Files[select].Name;
XDocument document = XDocument.Load(@"C:\Users\lab\Desktop\copy\spectro\" + namefile);

Console.WriteLine("Inserisci lelemento chimico da modificare:");
var chimical = Console.ReadLine();

var nodes = (from n in document.Descendants("ControlItems")
             where n.Element("ControlItem").Attribute("Name").Value == chimical
             select new
             {
                 nodeLimitValueLW = (string)n.Element("LimitValue").Attribute("Type") == "LowerWarningLimit",
                 nodeLimitValueUW = (string)n.Element("LimitValue").Attribute("Type") == "UpperWarningLimit",
                 nodeLimitValueLA = (string)n.Element("LimitValue").Attribute("Type") == "LowerAcceptanceLimit",
                 nodeLimitValueUA = (string)n.Element("LimitValue").Attribute("Type") == "UpperAcceptanceLimit"
             }).ToList();

foreach (var n in nodes)
{
    Console.WriteLine(n.nodeLimitValueLW);
    Console.WriteLine(n.nodeLimitValueUW);
    Console.WriteLine(n.nodeLimitValueLA);
    Console.WriteLine(n.nodeLimitValueUA);
}

This is my XML: 这是我的XML:

<GradeLimits GradeName="1.5217" GradeDescription="20MnV6" Norm="TXC03" BaseElement="Fe">
    <ControlItems>
        <ControlItem Name="C" DisplayUnit="%">
            <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.15999999642372131</LimitValue>
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.2199999988079071</LimitValue>
            <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.15000000596046448</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.23000000417232513</LimitValue>
        </ControlItem>
        <ControlItem Name="Si" DisplayUnit="%">
            <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.10000000149011612</LimitValue>
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.5</LimitValue>
            <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.090000003576278687</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.51999998092651367</LimitValue>
        </ControlItem>
        <ControlItem Name="Pb" DisplayUnit="%">
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue>
        </ControlItem>
    </ControlItems>
</GradeLimits>

For example: 例如:

The user wants to edit the <LimitValue> of the <ControlItem> with the attribute Name="Si" 用户想要使用属性Name="Si"编辑<ControlItem><LimitValue>

They would type in the console "Si", and I would need to iterate on all <ControlItem> , until I find the <ControlItem> with the attribute Name="Si" . 他们将在控制台中键入“ Si”,并且我需要遍历所有<ControlItem> ,直到找到具有<ControlItem> Name="Si"属性的<ControlItem>为止。 I would then need to take all the <LimitValue> and give the possibility to edit it. 然后,我需要使用所有<LimitValue>并提供对其进行编辑的可能性。

I hope I have explained it well. 我希望我已经解释清楚了。 Thanks in advance for the help. 先谢谢您的帮助。

Does not fully use Linq, but works for what you need. 没有完全使用Linq,但是可以满足您的需求。

    public class Limits
    {
        public string LowerWarningLimit = "";
        public string UpperWarningLimit = "";
        public string LowerAcceptanceLimit = "";
        public string UpperAcceptanceLimit = "";
    }

    public static void GetLimits(string nameFile)
    {
        XDocument document = XDocument.Load(nameFile);
        if (document == null)
        {
            Console.WriteLine("Document not found.");
            return;
        }

        XElement root = document.Descendants("ControlItems").FirstOrDefault();
        if (root == null)
        {
            Console.WriteLine("Could not find ControlItems.");
            return;
        }

        Console.WriteLine("Inserisci lelemento chimico da modificare:");
        var chimical = Console.ReadLine();
        XElement nameSearch = root.Descendants("ControlItem").FirstOrDefault(x => x.Attribute("Name") != null && x.Attribute("Name").Value.ToLower() == chimical.ToLower());
        if (nameSearch == null)
        {
            Console.WriteLine("Name not found.");
            return;
        }

        Limits limits = new Limits();
        foreach (XElement elements in nameSearch.Descendants())
        {
            string typeResult = elements.Attribute("Type").Value;
            if (typeResult == null)
            {
                continue;
            }

            switch (typeResult)
            {
                case "LowerWarningLimit":
                    limits.LowerWarningLimit = elements.Value;
                    break;

                case "UpperWarningLimit":
                    limits.UpperWarningLimit = elements.Value;
                    break;

                case "LowerAcceptanceLimit":
                    limits.LowerAcceptanceLimit = elements.Value;
                    break;

                case "UpperAcceptanceLimit":
                    limits.UpperAcceptanceLimit = elements.Value;
                    break;
            }
        }

        Console.WriteLine(limits.LowerWarningLimit);
        Console.WriteLine(limits.UpperWarningLimit);
        Console.WriteLine(limits.LowerAcceptanceLimit);
        Console.WriteLine(limits.UpperAcceptanceLimit);
    }
 static void Main(string[] args)
    {
        string xmlFilePath = @"C:\Users\vincenzo.lanera\Desktop\test.xml";
        XmlDocument document = new XmlDocument();
        document.Load(xmlFilePath);

        Console.WriteLine("Inserisci l'elemento chimico da modificare:");
        var chimical = Console.ReadLine();

        //Searches the limit values of the selected element
        XmlNodeList limitValues = document.SelectNodes($"//ControlItem[@Name='{chimical}']/LimitValue");

        //Prints all limit values
        Console.WriteLine($"Limit values of {chimical}:");
        foreach (XmlNode limVal in limitValues)
        {
            Console.WriteLine($"{limVal.Attributes["Type"].Value} {limVal.InnerText}");
        };

        //Ask the user wich limit value wants to edit
        Console.WriteLine("Inserisci il limit value da modificare:");
        var limitValueToEdit = Console.ReadLine();

        //Ask the user the new value
        Console.WriteLine("Inserisci il nuovo valore:");
        var newVal = Console.ReadLine();

        //Edit the limit value
        var nodeToEdit = document.SelectSingleNode($"//ControlItem[@Name='{chimical}']/LimitValue[@Type='{limitValueToEdit}']");
        nodeToEdit.InnerText = newVal;

        //Save the changes to the xml file
        document.Save(xmlFilePath);
    }
}

You should also handle the errors if the user inserts an invalid text. 如果用户插入无效的文本,您还应该处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM