C# 在xml文件中从用户搜索元素

C# 在xml文件中从用户搜索元素,c#,xml,search,C#,Xml,Search,我有一个任务是做一个搜索选项,我必须从键盘上找到输入,比如说一系列数字。找到它后,我必须查看整个.xml元素,编辑其中的一部分,最后将其放入.txt文件中 因此,您应该编写一个数字以在xml中搜索,然后使用所需的数字更改“instock”的值,更改后,将其放入txt中。但只有那个。所有数字(我搜索的代码和应该添加的instock值)都必须通过键盘输入。这是这里的主要问题 老实说,我不知道怎么做,我什么都试过了,什么都没用。它只会弹出错误 试试这个 using System; using

我有一个任务是做一个搜索选项,我必须从键盘上找到输入,比如说一系列数字。找到它后,我必须查看整个.xml元素,编辑其中的一部分,最后将其放入.txt文件中




因此,您应该编写一个数字以在xml中搜索,然后使用所需的数字更改“instock”的值,更改后,将其放入txt中。但只有那个。所有数字(我搜索的代码和应该添加的instock值)都必须通过键盘输入。这是这里的主要问题

老实说,我不知道怎么做,我什么都试过了,什么都没用。它只会弹出错误

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement art = doc.Descendants("art").Where(x => (string)x.Attribute("code") == "0356").FirstOrDefault();
            art.SetAttributeValue("instock", "456");

            doc.Save(FILENAME);
        }
    }
}

再解释一下。输入是什么?你总是想更新
instock
元素吗?这个问题很模糊。如果你能更具体一点就太好了你好,欢迎来到Stack Overflow!我对你的问题进行了编辑,以明确你的意图和标点符号。这使得回答问题的人更容易阅读问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement art = doc.Descendants("art").Where(x => (string)x.Attribute("code") == "0356").FirstOrDefault();
            art.SetAttributeValue("instock", "456");

            doc.Save(FILENAME);
        }
    }
}