gpt4 book ai didi

c# - 使用 XmlDictionaryReader 从消息中获取值

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:01 24 4
gpt4 key购买 nike

我需要从我的 WCF 消息中获取一个值。我的消息在调试器中具有以下值:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IBrokerService/SaveAndPrint</Action>
</s:Header>
<s:Body>
<SaveAndPrint xmlns="http://tempuri.org/">
<contract xmlns:d4p1="http://schemas.datacontract.org/2004/07/BrokerService.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:ContainerHistoryContracts i:nil="true" />
<!--Lots of nodes removed for brevity-->
<d4p1:CurrentBagId>123456</d4p1:CurrentBagId>
<!--Lots more nodes removed for brevity-->
<d4p1:WorkStation>TheNeededValue</d4p1:WorkStation>
</contract>
</SaveAndPrint>
</s:Body>
</s:Envelope>

但尽我所能,我无法使用 XmlDictionaryReader 获取 d4p1:WorkStation 值。有人知道如何使用 XmlDictionaryReader 执行此操作吗?

注意:我尝试使用 TypedMessageConverter,但是生成的类没有 MessageContract 的属性(尽管它们确实有 DataContract)

更新:我所拥有的不起作用。但是如果你想看到它,就在这里:

        // Load the message into an xml doc
var navigator = buffer.CreateNavigator();
MemoryStream memoryStream = new MemoryStream();
XmlWriter xmlWriter = XmlWriter.Create(memoryStream);
navigator.WriteSubtree(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;

XDocument xdoc = XDocument.Load(XmlReader.Create(memoryStream));
var workstationElement =
xdoc.Descendants(XName.Get("StringValue",
@"/s:Envelope[@xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""]/s:Body/SaveAndPrint[@xmlns=""http://tempuri.org/""]/contract[@xmlns:d4p1=""http://schemas.datacontract.org/2004/07/BrokerService.Contracts""]/d4p1:WorkStation"));

最佳答案

试试 xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication6
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
//using unique keys
Dictionary<string, string> dict1 = doc.Descendants().Where(x => x.Name.LocalName == "contract").FirstOrDefault().Elements()
.GroupBy(x => x.Name.LocalName, y => ((string)y).Trim())
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
//when there are duplicate keys
Dictionary<string, List<string>> dict2 = doc.Descendants().Where(x => x.Name.LocalName == "contract").FirstOrDefault().Elements()
.GroupBy(x => x.Name.LocalName, y => ((string)y).Trim())
.ToDictionary(x => x.Key, y => y.ToList());


}
}
}

关于c# - 使用 XmlDictionaryReader 从消息中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com