Generate comma delimited string from xml without using XSLT
我有一个如下所列的 XML。我需要创建一个逗号分隔的
注意:目前我正在遍历每个节点 - 但我正在寻找更好的方法
参考
XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <root> <AdvShipNotices> <AdvancedShipNotice>6D23513</AdvancedShipNotice> <StatusCD>OS</StatusCD> <CreatedOnDate>2014-03-28T11:08:16.750</CreatedOnDate> <TextilePlantCD>6D </TextilePlantCD> </AdvShipNotices> <AdvShipNotices> <AdvancedShipNotice>6D23514</AdvancedShipNotice> <StatusCD>OS</StatusCD> <CreatedOnDate>2014-03-28T11:08:16.750</CreatedOnDate> <TextilePlantCD>6D </TextilePlantCD> </AdvShipNotices> </root> |
VB.Net
1 2 3 4 | Dim objXML As New XmlDocument Dim asnString As String asnString ="<root>" & objASN.GetAdvShipNotices(containerScanParameter.PlantCD, containerScanParameter.UserID, , ,"OS") &"</root>" objXML.LoadXml(asnString) |
你可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | StringReader reader = new StringReader( @" <doc> <e>a</e> <e>b</e> <e>c</e> <e>d</e> <e>e</e> </doc>".Trim() ) ; XmlDocument xml = new XmlDocument() ; xml.Load( reader ) ; IEnumerable<string> texts = xml .SelectNodes("//*[text()]" ) .Cast<XmlNode>() .Select( x => x.InnerText ) ; string csv = String.Join("," , texts ) ; |
最后,
根据您的 XML 结构,您可能需要调整 XPath 表达式以适应。
另一种方法使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | string xml = @"<root> <AdvShipNotices> <AdvancedShipNotice>6D23513</AdvancedShipNotice> <StatusCD>OS</StatusCD> <CreatedOnDate>2014-03-28T11:08:16.750</CreatedOnDate> <TextilePlantCD>6D </TextilePlantCD> </AdvShipNotices> <AdvShipNotices> <AdvancedShipNotice>6D23514</AdvancedShipNotice> <StatusCD>OS</StatusCD> <CreatedOnDate>2014-03-28T11:08:16.750</CreatedOnDate> <TextilePlantCD>6D </TextilePlantCD> </AdvShipNotices> </root>" ; XDocument doc = XDocument.Parse( xml ) ; string csvFile = string.Join( Environment.NewLine , doc .Root .Elements() .Select( e => string.Join("," , e .Elements() .Select( c => c.Value ) ) ) ) ; |
产生这个文本
1 2 | 6D23513,OS,2014-03-28T11:08:16.750,6D 6D23514,OS,2014-03-28T11:08:16.750,6D |