2013-08-22 9 views
7

Mam więc XElement, który zawiera wiele elementów podrzędnych. Można pomyślnie zadeklarować Xelement i zapisać go do pliku:Jak zdobyć elementy dziecięce i wnuki z elementu XML?

Test.project:

<?xml version="1.0" encoding="utf-8"?> 
<project> 
    <child> 
     <grand-child1> 
      <great-grand-child1>Hello There!</great-grand-child1> 
      <great-grand-child2>Hello World!</great-grand-child2> 
     </grand-child1> 
     <grand-child2>Testing 123...</grand-child2> 
    </child> 
</project> 

Wtedy staram się czytać z pliku. Szukałem sposobów, aby uzyskać węzły dziecko i grand-dziecko, i znalazłem, że mogę użyć XElement.XPathSelectElement(). Problem polega na tym, że Visual C# nie rozpoznaje XPathSelectElement jako metody dla XElement. Szukałem przykładów użycia tej metody i wszyscy mówią, że używają XElement.XPathSelectElement.

Na przykład, próbowałem:

x_el = new XElement("project", 
    new XElement("child", 
     new XElement("grand-child", "Hello World!") 
); 

string get_string = x_el.XPathSelectElement("child/grand-child"); 

... ale XPathSelectElement nie jest rozpoznawany. Co ja robię źle?

+1

mieć dodać odwołanie do 'System.Xml .Linq'? – Damith

+1

@JuStDaN Mam napisany kod. Będę edytować mój post. – Dominoed

+0

@Damith Tak, to jest w tej samej klasie co miejsce, w którym utworzę XElement i zapiszę do pliku. – Dominoed

Odpowiedz

4

Trzeba dodać System.Xml.XPath nazw oraz jak

using System.Xml.XPath; 

po tym spróbować poniżej

x_el = new XElement("project", 
    new XElement("child", 
     new XElement("grand-child", "Hello World!") 
)); 
// XPathSelectElement method return XElement not string , use var or XElement 
XElement element = x_el.XPathSelectElement("child/grand-child"); 
string get_string = element.ToString() 

Albo

var get_string = x_el.XPathSelectElement("child/grand-child").ToString(); 
+0

Czy przeczytałeś moje pytanie? :/Próbowałem tego. – Dominoed

+0

Błąd: "System.Xml.Linq.XElement" nie zawiera definicji "XPathSelectElement" i nie można znaleźć metody rozszerzenia "XPathSelectElement" akceptującej pierwszy argument typu "System.Xml.Linq.XElement". brakuje dyrektywy użycia lub odwołania do zespołu?) – Dominoed

Powiązane problemy