繁体   English   中英

Linq XML NullReference读取元素列表时发生异常

[英]Linq XML NullReference Exception on reading list of elements

我正在尝试从Xml文件中读取文本节点列表。 当我尝试读取列出的文本元素中的1个的子节点时,即使XDocument节点似乎已被填充,也会出现NullReference异常。 NullReference异常会在foreach (XElement textElement in textElements)行上抛出foreach (XElement textElement in textElements)这意味着列表textElements的Count> 1,因此它不应为null。 这就是调试器愿意使用的范围。

我是否以错误的方式阅读Xml,还是不应该/不应该以现在的方式构建XElement列表?

这是我的Xml文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Book SYSTEM "Book.dtd"[]>
<album version="0.2" settingsVersion="1">
  <size />
  <cover />
  <inner>
    <page>
      <pagenumber>1</pagenumber>
      <image>1.jpg</image>
      <text>
        <value>Test </value>
        <font>arial</font>
        <size>18pt</size>
        <style>normal</style>
        <weight>normal</weight>
        <color>#77DD44</color>
        <rotation>0</rotation>
        <alignment>start</alignment>
        <position>
          <x>50</x>
          <y>50</y>
        </position>
      </text>
      <text>
          <value>Test 2 </value>
          <font>arial</font>
          <size>18pt</size>
          <style>normal</style>
          <weight>normal</weight>
          <color>#77DD44</color>
          <rotation>0</rotation>
          <alignment>start</alignment>
          <position>
             <x>50</x>
             <y>50</y>
          </position>
       </text>
    </page>
  </inner>
</album>

元素inner可以容纳多个page元素,而page可以容纳多个text元素。

我通过以下方法阅读Xml。

List<XElement> pageElements = doc.Root.Element("inner").Elements("page").ToList();
foreach (XElement pageElement in pageElements)
{
    string pageNumberString = pageElement.Element("pagenumber").Value;
    int pageNumberValue = Convert.ToInt32(pageNumberString);
    string fileNameValue = pageElement.Element("image").Value;
    // Verify if the currently looped page is the same as the one selected by the user.
    if (pageNumberValue == pageNumber)
    {
        // Get all text nodes from the found page.
        List<XElement> textElements = pageElement.Elements("text").ToList();
        // If no text nodes found return the page with an empty TextInfo array.
        if (textElements.Count == 0)
        {
            PageInfo pageInfoNoText = new PageInfo { PageNumber = pageNumberValue, FileName = fileNameValue, Text = new TextInfo[0] };
            Logger.log("PageInfo found for collection {0}. Info {1}", collectionId, pageInfoNoText);
            return pageInfoNoText;
        }
        // If text nodes are found build a list of TextInfo objects and build a new PageInfo object.
        else
        {
            // All text elements in the XML under the found page.
            List<TextInfo> textInfoList = new List<TextInfo>();
            TextInfo[] textArray = new TextInfo[0];

            #region  Load all required text data from the XML file and build the textList.
            foreach (XElement textElement in textElements)
            {
                string textValue = textElement.Element("value").Value;

                string fontValue = textElement.Element("font").Value;

                string fontSizeValue = textElement.Element("size").Value;

                string styleValue = textElement.Element("style").Value;

                string weightValue = textElement.Element("weight").Value;

                string colorValue = textElement.Element("color").Value;

                string rotationString = textElement.Element("rotation").Value;
                int rotationValue = Convert.ToInt32(rotationString);

                string alignmentValue = textElement.Element("alignment").Value;

                string positionXString = textElement.Element("x").Value;
                int positionXValue = Convert.ToInt32(positionXString);

                string positionYString = textElement.Element("y").Value;
                int positionYValue = Convert.ToInt32(positionYString);

                // Build Info objects.
                PositionInfo tempPositionInfo = new PositionInfo
                {
                    X = positionXValue,
                    Y = positionYValue
                };

                TextInfo tempTextInfo = new TextInfo
                {
                    Value = textValue,
                    Font = fontValue,
                    Size = fontSizeValue,
                    Style = styleValue,
                    Weight = weightValue,
                    Color = colorValue,
                    Rotation = rotationValue,
                    Alignment = alignmentValue,
                    Position = tempPositionInfo
                };

                textInfoList.Add(tempTextInfo);

            }
            textArray = textInfoList.ToArray();
            #endregion

            PageInfo pageInfo = new PageInfo
            {
                PageNumber = pageNumberValue,
                FileName = fileNameValue,
                Text = textArray
            };
            Logger.log("PageInfo found for collection {0}. Info: {1}", collectionId, pageInfo);
            return pageInfo;

        }
    }
}

任何帮助/见解表示赞赏!

您的文本元素不包含名为x的元素,因此尝试访问x的值将导致NullReferenceException:

string positionXString = textElement.Element("x").Value;
// textElement.Element("x") is null, "x" is in textElement.Element("position")
int positionXValue = Convert.ToInt32(positionXString);

为此,您最好使用Descendants(Descendants(“ x”)。FirstOrDefault()?. Value)代替Element,但总的来说,您可能希望完全对其进行重组。

您的代码很好,但是当获取x和y值时出现错误,您需要获取position元素的x和y值,如下所示

string positionXString = (string)textElement.Element("position").Element("x").Value;
int positionXValue = Convert.ToInt32(positionXString);
string positionYString = (string)textElement.Element("position").Element("y").Value;
int positionYValue = Convert.ToInt32(positionYString);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM