peter
peter

Reputation: 8652

how to get value from xml by Linq

i was reading huge xml file of 5GB size by using the following code, and i was success to get the first element Testid but failed to get another element TestMin coming under different namespace this is the xml i am having

 which i am getting as null

.What is wrong here?

EDIT GMileys answer giving error like The ':' character, hexadecimal value 0x3A, cannot be included in a name

Upvotes: 3

Views: 98

Answers (4)

peter
peter

Reputation: 8652

actually namespace was the culprit,what i did is first loaded the small section i am getting from.Readform method in to xdocument,then i removed all the namespace,then i took the value .simple :)

Upvotes: 0

jdweng
jdweng

Reputation: 34421

try this code which is very similar to your code but simpler.

            using (XmlReader xr = XmlReader.Create(path))
            {
                 xr.MoveToContent();
                 XNamespace un = xr.LookupNamespace("un");
                 XNamespace xn = xr.LookupNamespace("xn");
                 XNamespace es = xr.LookupNamespace("es");
                 while (!xr.EOF)
                 {
                     if(xr.LocalName != "UtranCell")
                     {
                         xr.ReadToFollowing("UtranCell", un.NamespaceName);
                     }
                     if(!xr.EOF)
                     {
                         XElement utranCell = (XElement)XElement.ReadFrom(xr);
                     }
                }
            }

Upvotes: 1

gmiley
gmiley

Reputation: 6604

The element es:qRxLevMin is a child element of xn:attributes, but it looks like you are trying to select it as a child of xn:vsDataContainer, it is a grandchild of that element. You could try changing the following:

var dataqrxlevmin = from atts in pin.ElementsAfterSelf(xn + "VsDataContainer")
        select new
        {
            qrxlevmin = (string)atts.Element(es + "qRxLevMin"),
        };

To this:

var dataqrxlevmin = from atts in pin.Elements(string.Format("{0}VsDataContainer/{1}attributes", xn, es))
        select new
        {
            qrxlevmin = (string)atts.Element(es + "qRxLevMin"),
        };

Note: I changed your string concatenation to use string.Format for readability purposes, either is technically fine to use, but string.Format is a better approach.

Upvotes: 3

Gabor
Gabor

Reputation: 3246

What about this approach?

XDocument doc = XDocument.Load(path);

XName utranCellName = XName.Get("UtranCell", "un");
XName qRxLevMinName = XName.Get("qRxLevMin", "es");

var cells = doc.Descendants(utranCellName);

foreach (var cell in cells)
{
    string qRxLevMin = cell.Descendants(qRxLevMinName).FirstOrDefault();

    // Do something with the value
}

Upvotes: 1

Related Questions