XML Editing: How can I get the value of a property

Asked

Viewed 601 times

2

I have a question to read and edit an XML in C Sharp. I need to get the value of the attribute "uuid" of the "Machine" node, this one is in the "Virtualbox" node. I also want the "Location" and "uuid" properties of each of the "Harddisk" nodes, as in the image. Here is the XML file link

Propriedades desejadas

I made this code with the help of the user psNytrancez. Catch the uuid of Machine works, but to go to a lower level, in `Harddisk , I could not result.

var doc = XDocument.Load(@"Z:\Área de Trabalho\Windows XP.xml");
var no = doc.Root.Element("Machine");
foreach (var elemento in doc.Root.Elements())
{
    if (elemento.Name.LocalName == "Machine")
    {
        Console.WriteLine("Anterior: -" + elemento.Attribute("uuid").Value + "-");
        break;
        // Essa parte funciona perfeitamente.
    }
}

foreach (var elemento in doc.Root.Elements())
{
    if (elemento.Name.LocalName == "HardDisk")
    {
        Console.Write("-" + elemento.Attribute("uuid").Value + "-");
        Console.WriteLine("-" + elemento.Attribute("location").Value + "-");
        //Mas esta não lista nenhum resultado, sendo que tem dois no arquivo XML
    }
}

The most interesting for me is a for or foreach to go through each of the sub nodes of HardDisks, so no matter the number of us.

Thanks people.

  • 1

    Can you please replace the image XML with text? I would like to run some tests here.

  • I put an answer but in order to ensure that it will work please put the full xml.

  • Thanks anyway. Your code worked right, but now I have a different problem. I supplemented my question, Now I need to get the value of a node at a lower level and my adaptation of what you gave me doesn’t work in this case.Open the XML link, the file is now another but has the same structure

1 answer

1


var valorUuid = "";
var doc = XDocument.Load(@"Z:\Área de Trabalho\Windows Vista.xml");
var machine = doc.Root.Element("Machine");
foreach (var element in doc.Root.Elements())
{
   if (element.Name.LocalName == "Machine") 
   {
       valorUuid = element.Attribute("uuid").Value;
       break;
   }
}
  • Was a mistake O membro 'System.Xml.Linq.XDocument.Load(string)' não pode ser acessado com uma referência de instância; qualifique-o com o nome do tipo. The XML link is that

  • @Marcelonascimento is now working!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.