-1

これはファイルからの私の XML データです

<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml" />
<item id="W000Title" href="000Title.html" media-type="application/xhtml+xml" />
<item id="W01MB154" href="01MB154.html" media-type="application/xhtml+xml" />
<item id="WTOC" href="TOC.html" media-type="application/xhtml+xml" />

Store アプリケーションで C# を使用して要素の値を取得したいと考えています。値を取得していますが、正しい方法ではなく、次のステップに進むことができません。

    string fileContents3 = await FileIO.ReadTextAsync(file);
    xmlDoc1.LoadXml(fileContents3);
    XmlNodeList item = xmlDoc1.GetElementsByTagName("item");
    for (uint k = 0; k < item.Length; k++)
    {
        XmlElement ele1 = (XmlElement)item.Item(k);
        var attri1 = ele1.Attributes;
        var attrilist1 = attri1.ToArray();
        for (int l = 0; l < attrilist1.Length; l++)
        {
            if (attrilist1[l].NodeName == "id")
            {

                    ids2 = attrilist1[0].NodeValue.ToString();
                    ids3 = attrilist1[1].NodeValue.ToString();
            }
        } 
   }

この方法ではなく、属性「id」の要素値を取得する方法を知りたい

4

3 に答える 3

0

XmlNodeオブジェクトの属性の値を取得する場合は、この関数を使用できます。

    public static string GetAttributeValue(XmlNode node, string attributeName)
    {
        XmlAttribute attr = node.Attributes[attributeName];
        return (attr == null) ? null : attr.Value;
    }
于 2013-05-20T12:04:30.797 に答える
0

XPath を使用する必要がある場合は、次のように使用できます。

      XmlDocument document = new XmlDocument();
        document.Load(@"c:\users\saravanan\documents\visual studio 2010\Projects\test\test\XMLFile1.xml");

        XmlNodeList itemNodes = document.SelectNodes("//item");

        foreach (XmlElement node in itemNodes)
        {
            if (node.Attributes.Count > 0)
            {
                if (node.HasAttribute("id"))
                {
                    Console.Write(node.Attributes["id"]);
                }

            }
        }

        var itemNodeswithAttribute = document.SelectNodes("//item[href=toc.ncx]");

        itemNodeswithAttribute = document.SelectNodes("//item[@href='toc.ncx']");
于 2013-05-20T12:23:29.390 に答える
0
string fileContents3 = await FileIO.ReadTextAsync(file);
xmlDoc1.LoadXml(fileContents3);
XmlNodeList item = xmlDoc1.GetElementsByTagName("item");
        for (uint k = 0; k < item.Length; k++)
        {
            XmlElement ele1 = (XmlElement)item.Item(k);
            string foo = ele1.Attributes[0].NodeValue.ToString();
        }

コードを少し簡略化しました。これがあなたを助けることを願っています。id 属性は常に最初の位置 (インデックス 0) にあると想定しています。

于 2013-05-20T17:52:24.890 に答える