Home > Back-end >  Unable to get values from xml nodes
Unable to get values from xml nodes

Time:04-29

I am trying to parse through xml and get some values and have tried multiple approaches but i am unable to get the values.

this is what i have tried so far

        string fileName = @"C:\Users\one\OneDrive\Desktop\PP\SnippetWithImage.idms";
        string xmlString = System.IO.File.ReadAllText(fileName);

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(fileName);
        XmlNodeList spreadNodes = xmlDoc.GetElementsByTagName("spread");
        foreach (XmlNode spreadNode in spreadNodes)
        {
            var linkNodes = spreadNode.SelectNodes("//rectangle/image/link");
            foreach (XmlNode linkNode in linkNodes)
            {
                Console.WriteLine("path : "   linkNode.SelectSingleNode("LinkResourceURI").InnerText);
            }
        }

Here spreadNodes count is always 0.

I have tried this with XElements as well and used Decendents but sill the same result.

Here is the xml structure https://codebeautify.org/xmlviewer/y22db1f26

the file which i am loading is an InDesign Snippet file. I am trying to get the linkResourceURI property value from links which is a child of image which is a child of rectangle which is a child of spread.

CodePudding user response:

Some quick debugging shows that spreadNodes is empty, to start with. The most obvious cause is that the element name is Spread not spread, and if we make this change, we see spreadNodes has one element.

Next, it's obvious that spreadNode.SelectNodes("//rectangle/image/link") isn't returning anything. Again, that's probably capitalisation: change it to //Rectangle/Image/Link, and we get a NullReferenceException. Progress, at least.

We're getting that exception because linkNode.SelectSingleNode("LinkResourceURI") is returning null. It turns out that's because LinkResourceURI is an attribute, and you're looking for an element. Change that to linkNode.Attributes["LinkResourceURI"].InnerText, and everything works as expected.

XmlNodeList spreadNodes = xmlDoc.GetElementsByTagName("Spread");
foreach (XmlNode spreadNode in spreadNodes)
{
    var linkNodes = spreadNode.SelectNodes("//Rectangle/Image/Link");
    foreach (XmlNode linkNode in linkNodes)
    {
        Console.WriteLine("path : "   linkNode.Attributes["LinkResourceURI"].InnerText);
    }
}
  • Related