2

I have an xml file like this one:

    <root>
       <sub>
          <name>Al</name>
          <code>001</code>
       </sub>
       <sub>
          <name>John</name>
          <code>002</code>
       </sub>

and a List<string> lName= new List<string>(new string[] { "Jack", "John"});

I want to edit "John" node, add "Jack" node and leave "Al" node as it is. What I did is:

System.Xml.XmlNodeList nodeNameList = FileXml.SelectNodes(@"//*[contains(name(),'name')]");
foreach (string name in lName)
{
   System.Xml.XmlNode nodeName=FileXml.SelectSingleNode("//root/sub/name");                 
   if (nodeName.InnerText == name)
   {
        //add
   }
   else
   {
        //edit              
   }

But it doesn't work. I thought that XmlNodeList works as a normal list but it doesn't. Can someone help me?

2 Answers 2

1

YOu can load your xml into the Document and then use Descendants with node name and then apply the Where filter on it with Contins. You can try something like this,

    XDocument xmlDocument = XDocument.Load(@"yourxmlpath.xml");
    var result = xmlDocument.Descendants("sub")
                .Where(x => lName.Contains(x.Element("name").Value)).ToList();
Sign up to request clarification or add additional context in comments.

12 Comments

If you're going to pursue this solution, I'd advise just using an XDocument from the start and avoiding the whole XmlDocument API. XDocument is easier to work with and will perform better in many scenarios. However, if he has to use the XmlDocument API I'd avoid using LINQ to XML - if you've already loaded the document and the DOM for it, just stick with it.
Do you mean I can do this without using Linq? I would prefer to use only System.Xml since my whole code is based on it
Xdocument is in the same namespace. That is System.xml.Linq and it is using linq. And it is XML-Linq it will perform better (I think) and clean and understandable code.
Yes I know, but in this way shouldn't I load the document 2 times?
Why the 2 times ? You can load once at start and perform all operations on that document.
|
0

You've got a couple problems here.

First, you're comparing an XmlNode to a string with this code:

if (nodeName == name)

Which will never evaluate as true. You want something like

if (nodeName.InnerText == name)

For your add logic, you'll need to create a new XmlNode and append it (see https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild%28v=vs.110%29.aspx). For your update logic, just set the InnerText property on the node.

1 Comment

Yes sorry, actually I compare 2 string in that if(). I just cutted too much code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.