Linq To XML:获得自身结点,及相邻的上/下一个结点

XElement firstParticipant; // A full document with all the bells and whistles. XDocument xDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XDocumentType("BookParticipants", null, "BookParticipants.dtd", null), new XProcessingInstruction("BookCataloger", "out-of-print"), // Notice on the next line that we are saving off a reference to the first // BookParticipant element. new XElement("BookParticipants", new XComment("Begin Of List"), firstParticipant = new XElement("BookParticipant", new XAttribute("type", "Author"), new XElement("FirstName", "Joe"), new XElement("LastName", "Rattz")), new XElement("BookParticipant", new XAttribute("type", "Editor"), new XElement("FirstName", "Ewan"), new XElement("LastName", "Buckingham")), new XComment("End Of List"))); foreach (XNode node in firstParticipant.NodesAfterSelf()) { Console.WriteLine(node); }  

 

上面给firstParticipant结点前后加了两个XComment结点、

因此打印结果是这样的

 

<BookParticipant type="Editor"> <FirstName>Ewan</FirstName> <LastName>Buckingham</LastName> </BookParticipant> <!--End Of List-->  

 

上面已经把相邻的元素"<!--End Of List-->"也打印出来了

 

 

那么只想打印下一个XElement怎么办呢,当然可以再用TypeOf,但还有个更简便的方法,

就是XNode.ElementsAfterSelf() 

 

上面循环写成这样

 

foreach (XNode node in firstParticipant.ElementsAfterSelf())  

 

那么结果只有元素出现了

 

<BookParticipant type="Editor"> <FirstName>Ewan</FirstName> <LastName>Buckingham</LastName> </BookParticipant>  

 

相应的还有XNode.NodesBeforeSelf() ,XNode.ElementsBeforeSelf() 

道理是一样的,不再写出打印结果了

你可能感兴趣的:(Linq To XML:获得自身结点,及相邻的上/下一个结点)