我有一个XML,如下所示。我需要创建一个以逗号分隔的AdvancedShipNotice
值字符串。我们如何使用XPath而不使用XSLT?
注意:目前我正在循环throgh每个节点 - 但我正在寻找更好的方法
参考
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>
VB.Net
Dim objXML As New XmlDocument
Dim asnString As String
asnString = "<root>" & objASN.GetAdvShipNotices(containerScanParameter.PlantCD, containerScanParameter.UserID, , , "OS") & "</root>"
objXML.LoadXml(asnString)
答案 0 :(得分:1)
您可以这样做:
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 ) ;
最后,csv
应保留a,b,c,d,e
。
根据XML的结构,您可能必须调整XPath外推以适应。
另一种方法使用XDocument
。对于您的示例文档,这样的内容将起作用:
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 )
)
)
) ;
制作此文
6D23513,OS,2014-03-28T11:08:16.750,6D
6D23514,OS,2014-03-28T11:08:16.750,6D