简体   繁体   中英

c# XML and LINQ

I have an XML doc that looks like so:

<people>
  <person>
    <name>mike</name>
    <address>1 main st</address>
    <jobTitle>SE</jobTitme>
       <children>
           <name>mary</name>
           <age>5</age>
       </childres> 
  </person>
  <person>
    <name>john</name>
    <address>2 main st</address>
    <jobTitle>SE</jobTitme>
  </person>
</people>`

So not all of the person blocks and a children block. Pretty simple. When I add a new person to the XML via C#, I am writing a function that takes a person object and that person object has a collection of children objects (which may be 0 or more). I am having trouble writing the linq in that function. I can easily add a person object, but conditionally adding 1 or more children is tough. Here is what I have so far:

    doc.Element("People").Add(
            new XElement("Person", 
                new XElement("Name", person.name),
                new XElement("Address", person.address),
                new XElement("jobTitle", person.jobTitle)))

how can I conditionally add the children if they exist?

public class person { public List<Child> childList; public string name; public string address; public string jobTitle }

public class child { public string name; public int age; }

how can I conditionally add the children if they exist?

Three options:

  • Use a null argument in the XElement call; that will be ignored
  • Pass in an empty sequence of children; again, this will be irrelevant
  • Build the rest of the element, then just conditionally call Add afterwards.

It's hard to give more concrete advice without seeing the code for your Person type.

(As an aside, it looks like your element should actually be child rather than children, assuming that you have one element per child...)

EDIT: Now that we can see your code, it looks like you just want:

doc.Element("People").Add(
        new XElement("Person", 
            new XElement("Name", person.name),
            new XElement("jobTitle", job.title),
            person.children.Select(c => new XElement("children",
                new XElement("Name", c.name),
                new XElement("Age", c.age)))));

Note that you're currently being very inconsistent with your capitalization when it comes to element names, and also it's a bad idea to expose public fields like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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