0

私は次のようなxmlを持っています:

<?xml version="1.0" encoding="utf-8" ?> 
<response list="true">
    <count>10748</count> 
    <post>
        <id>164754</id>
        <text></text> 
        <attachments list="true">
            <attachment>
                <type>photo</type> 
                <photo>
                    <pid>302989460</pid> 
                </photo>
            </attachment>
        </attachments>

に があるかどうかを確認する必要があり<attachment>ます<post>。私はこのようなすべての投稿を取得しています:

XmlNodeList posts = XmlDoc.GetElementsByTagName("post");
foreach (XmlNode xnode in posts)
{
    //Here I have to check somehow
}

投稿にノードがない場合は、代わり<attachment>に取得したいと思います。<text>

4

3 に答える 3

1

から に変更するXmlDocumentXElement、LINQ クエリを使用してattachmentノードの数を取得できます。

//load in the xml
XElement root = XElement.Load("pathToXMLFile"); //load from file
XElement root = XElement.Parse("someXMLString"); //load from memory

foreach (XElement post in root.Elements("post"))
{
    int numOfAttachNodes = post.Elements("attachments").Count();

    if(numOfAttachNodes == 0)
    {
        //there is no attachment node
    }
    else
    {
        //something if there is an attachment node
    }
}
于 2013-05-09T00:49:37.870 に答える
0

次のようなlinqクエリを試すことができます

var result = XmlDoc.Element("response")
                   .Elements("post").Select(item => item.Element("attachments")).ToList();

foreach(var node in result)
{

}
于 2013-05-09T01:08:20.277 に答える
-1

「投稿」にノードがあるかどうかを確認するには:

if(posts.Count == 0)
{
    // No child nodes!
}

ループを開始する前にこれを行うことができます。

于 2013-05-09T00:33:28.867 に答える