Generate comma delimited string from xml without using XSLT
我有一个如下所列的 XML。我需要创建一个逗号分隔的 AdvancedShipNotice 值字符串。我们如何在不使用 XSLT 的情况下使用 XPath?
注意:目前我正在遍历每个节点 – 但我正在寻找更好的方法
参考
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) |
- 有什么尝试吗?所以我们不需要从头开始(遍历 AdvShipNotices 并用 String.Join 和 XmlNode.InnerText 构建一个字符串)…
- @AdrianoRepetti 目前我正在遍历每个节点-但我正在寻找更好的代码
- 在 XPath 2.0 中,您可以使用 string-join(/root/AdvShipNotices/AdvancedShipNotice, ‘,’)
你可以这样做:
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() ; IEnumerable<string> texts = xml |
最后,csv 应该持有 a,b,c,d,e.
根据您的 XML 结构,您可能需要调整 XPath 表达式以适应。
另一种方法使用 XDocument。对于您的示例文档,可以使用以下内容:
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 ) ; |
产生这个文本
1
2 |
6D23513,OS,2014-03-28T11:08:16.750,6D
6D23514,OS,2014-03-28T11:08:16.750,6D |
来源:https://www.codenong.com/24415606/