Hai bisogno di un piccolo aiuto con Linq 2 xml
-
19-08-2019 - |
Domanda
Ho uno scenario simile a questo:
public class TestLinq2Xml
{
private XElement GenerateSomeXml()
{
return XElement.Parse(@"<MyObject>
<Properties>
<Name>My object 1</Name>
<Position>0; 0; 0</Position>
</Properties>
</MyObject>");
}
public void ExploreXmlNode()
{
var xmlTree = this.GenerateSomeXml();
var name = xmlTree.Element("MyObject").Element("Properties").Element("Name").Value;
Console.WriteLine(name);
}
}
Ok, questo è molto semplificato. .... ma non funzionerà ancora. Qualche idea su cosa sto facendo di sbagliato qui?
Modifica:
Oh, quasi dimenticato. Il problema è che xmlTree.Element("MyObject")
restituisce una sequenza linq vuota. Anche se ho chiaramente un nodo chiamato & Quot; MyObject & Quot ;.
Soluzione
XElement.Parse restituisce un XElement che è il nodo <MyObject>
. Prova: -
var name = xmlTree.Element (" Proprietà "). Elemento (" Nome "). Valore;
Altri suggerimenti
Oltre a quanto suggerito dal poster precedente, puoi anche restituire un XDocument dalla tua funzione GenerateSomeXml () in modo che il tuo linq funzioni.
private static XDocument GenerateSomeXml()
{
return XDocument.Parse(@"<MyObject>
<Properties>
<Name>My object 1</Name>
<Position>0; 0; 0</Position>
</Properties>
</MyObject>");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow