<Notification>
<Id>04l5h0000002iBuAAI</Id>
<sObject xsi:type="sf:Social_Post__c" xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
<sf:Id>a015h00002LiNpbAAF</sf:Id>
</sObject>
</Notification>
用 C# 编写代码无法提取 a015h00002LiNpbAAF 此 id 在这里为空 有人可以帮忙吗
我正在使用的类
public class Notification
{
[XmlElement(ElementName = "Id", Namespace = "http://soap.sforce.com/2005/09/outbound")]
public string Id { get; set; }
[XmlElement(ElementName = "sObject", Namespace = "urn:sobject.enterprise.soap.sforce.com")]
public SObject SObject { get; set; }
}
public class SObject
{
[XmlElement(ElementName = "sObject", Namespace = "sf:urn:sobject.enterprise.soap.sforce.com")]
public string Id { get; set; }
}
我想从上面的 xml 中提取 sObjectId
自我回答这个问题:扭转你的思维。询问序列化器它现在期待什么,但要求它序列化某些东西。如果我们这样做:
var ser = new XmlSerializer(typeof(Notification));
ser.Serialize(Console.Out, new Notification { Id = "abc",
SObject = new SObject { Id = "def" } });
我们看到:
<Notification xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id xmlns="http://soap.sforce.com/2005/09/outbound">abc</Id>
<sObject xmlns="urn:sobject.enterprise.soap.sforce.com">
<sObject xmlns="sf:urn:sobject.enterprise.soap.sforce.com">def</sObject>
</sObject>
</Notification>
我们可以忽略两个
xmlns:
声明,但是我们可以看到 Notification.Id
位于错误的命名空间中,并且 SObject.Id
具有错误的元素名称(同样,我们基本上可以忽略别名与内联命名空间之间的差异;注意另外 sf:
不是命名空间的一部分)。所以,解决这个问题:
public class Notification
{
public string Id { get; set; }
[XmlElement(ElementName = "sObject")]
public SObject SObject { get; set; }
}
public class SObject
{
[XmlElement(Namespace = "urn:sobject.enterprise.soap.sforce.com")]
public string Id { get; set; }
}
现在我们可以反序列化:
var xml = """
<Notification>
<Id>04l5h0000002iBuAAI</Id>
<sObject xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
<sf:Id>a015h00002LiNpbAAF</sf:Id>
</sObject>
</Notification>
""";
var ser = new XmlSerializer(typeof(Notification));
var obj = (Notification) ser.Deserialize(new StringReader(xml));
Console.WriteLine(obj.Id);
Console.WriteLine(obj.SObject.Id);
(我还删除了未定义的
xsi:
用法)