C# 使用C对具有命名空间的同级元素进行XML解析
我有一个复杂的XML,希望使用LINQ在C中解析它:C# 使用C对具有命名空间的同级元素进行XML解析,c#,.net,xml,linq,linq-to-xml,C#,.net,Xml,Linq,Linq To Xml,我有一个复杂的XML,希望使用LINQ在C中解析它: <?xml version="1.0"?> <?mso-application progid="Word.Document"?> <w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint"
<?xml version="1.0"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:aml="http://schemas.microsoft.com/aml/2001/core" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xml:space="preserve" w:embeddedObjPresent="no">
<w:docPr xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">
<w:displayBackgroundShape/>
<w:view w:val="print"/>
<w:zoom w:percent=""/>
<w:defaultTabStop w:val="708.1365"/>
<w:docVars/>
</w:docPr>
<w:body>
<w:p xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">
<w:pPr>
<w:pStyle w:val="Author_28_s_29_"/>
</w:pPr>
<w:r>
<w:rPr><w:rStyle w:val="T4"/></w:rPr>
<w:t>Satyam</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T5"/>
</w:rPr>
<w:t>Singh</w:t>
</w:r>
<w:r>
<w:t>,</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T6"/>
</w:rPr>
<w:t>Disha</w:t>
</w:r>
<w:r>
<w:t>A</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T4"/>
</w:rPr>
<w:t>.</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T5"/>
</w:rPr>
<w:t>Shah</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T7"/>
</w:rPr>
<w:t>,2,*</w:t>
</w:r>
<w:r>
<w:t>,</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T4"/>
</w:rPr>
<w:t>Karan</w:t>
</w:r>
<w:r>
<w:rPr>
<w:rStyle w:val="T5"/>
</w:rPr>
<w:t>Bhutwala</w:t>
</w:r>
</w:p>
</w:body>
</w:wordDocument>
因此,我想得到如下信息:
作者:萨蒂亚姆·辛格
作者迪沙·沙阿
作者:卡兰·布特瓦拉
等等
我尝试了几个选项来解析。这里的逻辑可以理解为
parent.children.where.t.value这个xml非常奇怪。也许有更简单的方法,但我得到的只有:
XDocument xd = XDocument.Load("1.xml");
XNamespace nms = "http://schemas.microsoft.com/office/word/2003/wordml";
var author = xd.Root.Element(nms + "body")
.Descendants(nms + "pStyle")
.Single()
.Attribute(nms + "val").Value;
var arr = string.Join(" ", xd.Root.Element(nms + "body")
.Descendants(nms + "t").Select(y => y.Value))
.Split(',').Where(y => y.Length > 2)
.Select(y => string.Format("{0}={1}", author, y.Trim()))
.ToArray();
foreach (var x in arr)
Console.WriteLine(x);
输出:
请展示一个简短但完整的程序,说明你所做的尝试,并解释你的预期和发生的事情。如果您对XML进行格式化,使其结构清晰可见,这也会很有帮助。
Author_28_s_29_=Satyam Singh
Author_28_s_29_=Disha A . Shah
Author_28_s_29_=Karan Bhutwala