0

私は次のコードを持っています、

XDocument doc = XDocument.Parse(input);

var nodes = doc.Element(rootNode)
               .Descendants()
               .Where(n => 
                    (n.Value != "0" 
                    && n.Value != ".00" 
                    && n.Value != "false" 
                    && n.Value != "") 
                    || n.HasElements)
               .Select(n => new 
                { 
                    n.Name, 
                    n.Value, 
                    Level = n.Ancestors().Count() - 1, 
                    n.HasElements 
                });

var output = new StringBuilder();    
foreach (var node in nodes)
{
    if (node.HasElements)
    {
        output.AppendLine(new string(' ', node.Level) + node.Name.ToString() + ":");              
    }
else
{
}

私の問題は、親ノードに空の子ノードが 1 つしかない場合、余分な空白行を 1 行挿入する必要があることです。唯一の子が空かどうかを確認する方法がわかりませんでした。

を使用して子孫の数を取得できますが、Descendants = n.Descendants().Count()その唯一の子が空であるかどうかをテストする方法がわかりません。

4

2 に答える 2

2

私の理解では、子ノードが 1 つしかないすべての親ノードが必要であり、その子ノードは空です。

これを実現する簡単なテストを次に示します。例を具体的に使用するのではなく、タスクを実行します。あなたのXMLがどのように見えるかを提供する場合、以下があなたのプロジェクトに簡単に移植されない場合、あなたの投稿に合うように私の例を修正してみてください:)

(コンソール アプリから取得しましたが、実際にノードを取得するクエリは機能するはずです。

static void Main(string[] args)
{
    var xml = @"<root><child><thenode>hello</thenode></child><child><thenode></thenode></child></root>";
    XDocument doc = XDocument.Parse(xml);

    var parentsWithEmptyChild = doc.Element("root")
        .Descendants() // gets all descendants regardless of level
        .Where(d => string.IsNullOrEmpty(d.Value)) // find only ones with an empty value
        .Select(d => d.Parent) // Go one level up to parents of elements that have empty value
        .Where(d => d.Elements().Count() == 1); // Of those that are parents take only the ones that just have one element


    parentsWithEmptyChild.ForEach(Console.WriteLine);

    Console.ReadKey();
}

これは、空のノードを 1 つだけ含む 2 番目のノードのみを返します。ここで、empty は string.Empty の値であると想定されます。

于 2013-03-07T02:55:11.320 に答える
0

私はこの問題を自分で解決しようとしていましたが、これが私が思いついたものです:

XDocument doc = XDocument.Parse(input);

         var nodes = doc.Element(rootNode).Descendants()
             .Where(n => (n.Value != "0" && n.Value != ".00" && n.Value != "false" && n.Value != "") || n.HasElements)
             .Select(n => new { n.Name, n.Value, Level = n.Ancestors().Count() - 1, 
                n.HasElements, Descendants = n.Descendants().Count(), 
                FirstChildValue = n.HasElements?n.Descendants().FirstOrDefault().Value:"" });

         var output = new StringBuilder();

         foreach (var node in nodes)
         {            
            if (node.HasElements)
            {               
               output.AppendLine(new string(' ', node.Level) + node.Name.ToString() + ":");
               if (0 == node.Level && 1 == node.Descendants && String.IsNullOrWhiteSpace(node.FirstChildValue))
                  output.AppendLine("");
            }
于 2013-03-07T02:58:12.450 に答える