As *_*s k 3 c# linq linq-to-xml
这是我的xml文件
<Persons>
<Person>
<id>1</id>
<Name>Ingrid</Name>
</Person>
<Person>
<id>2</id>
<Name>Ella</Name>
</Person>
</Persons>
Run Code Online (Sandbox Code Playgroud)
我正在使用linq xml.
这里的id应该是自动生成的..
我需要检查node id的值是否已经存在.
如果不存在,它应该创建一个新的id ..如何使用linq这样做.任何指针?
谢谢
XDocument doc = XDocument.Parse(xml);
int id = 1;
// if you need the element
XElement ingrid = (from person in doc.Root.Elements("Person")
where (int)person.Element("id") == id
select person).FirstOrDefault();
// if you just need to know if it is there
bool exists = (from person in doc.Root.Elements("Person")
where (int)person.Element("id") == id
select person).Any();
// generate a new ID
int newId = ((from person in doc.Root.Elements("Person")
select (int?)person.Element("id")).Max() ?? 0) + 1;
Run Code Online (Sandbox Code Playgroud)