C# 中的后代没有给出正确的值
Descendants in C# do not give the right value
我是 XML 使用 C# 的新手,我有一个 XML 我需要通过父级中的特定子级
我需要获取 id 和调用变量 variables 我这样做了但每次都没有经过循环
我是否需要遍历 xml 的所有父级,直到得到我想要的树??
xml
<message xmlns="jabber:client" to="1072@finesse1.dcloud.cisco.com" id="/finesse/api/User/1072/Dialogs__1072@finesse1.dcloud.cisco.com__104Y2" from="pubsub.finesse1.dcloud.cisco.com">
<event xmlns="http://jabber.org/protocol/pubsub#event">
<items node="/finesse/api/User/1072/Dialogs">
<item id="460c2d27-c914-4c24-a95f-edf9f8df45c21535">
<notification xmlns="http://jabber.org/protocol/pubsub">
<Update>
<data>
<dialogs>
<Dialog>
<associatedDialogUri></associatedDialogUri>
<fromAddress>1071</fromAddress>
<id>18639330</id>
<mediaProperties>
<DNIS>1072</DNIS>
<callType>AGENT_INSIDE</callType>
<dialedNumber>1072</dialedNumber>
<outboundClassification></outboundClassification>
<callvariables>
<CallVariable>
<name>callVariable1</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable2</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable3</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable4</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable5</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable6</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable7</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable8</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable9</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable10</name>
<value></value>
</CallVariable>
</callvariables>
</mediaProperties>
<mediaType>Voice</mediaType>
<participants>
<Participant>
<actions>
<action>ANSWER</action>
</actions>
<mediaAddress>1072</mediaAddress>
<mediaAddressType>AGENT_DEVICE</mediaAddressType>
<startTime>2017-09-15T19:23:36.872Z</startTime>
<state>ALERTING</state>
<stateCause></stateCause>
<stateChangeTime>2017-09-15T19:23:36.872Z</stateChangeTime>
</Participant>
<Participant>
<actions>
<action>UPDATE_CALL_DATA</action>
<action>DROP</action>
</actions>
<mediaAddress>1071</mediaAddress>
<mediaAddressType>AGENT_DEVICE</mediaAddressType>
<startTime>2017-09-15T19:23:36.609Z</startTime>
<state>INITIATED</state>
<stateCause></stateCause>
<stateChangeTime>2017-09-15T19:23:36.819Z</stateChangeTime>
</Participant>
</participants>
<state>ALERTING</state>
<toAddress>1072</toAddress>
<uri>/finesse/api/Dialog/18639330</uri>
</Dialog>
</dialogs>
</data>
<event>POST</event>
<requestId></requestId>
<source>/finesse/api/User/1072/Dialogs</source>
</Update>
</notification>
</item>
</items>
</event>
</message>
那就是
代码
XElement xmlroots = XElement.Parse(parsingNewXML);
//Dialog = xmlroots.Element("Dialog").Value;
var CallVariable = parsingNewXML.Contains("CallVariable");
var startCall = parsingNewXML.Contains("ALERTING");
if (CallVariable == true && startCall == true)
{
foreach (XElement callID in xmlroots.Descendants("Dialog"))
{
DialogID = callID.Element("id").Value;
//System.Windows.MessageBox.Show(DialogID);
System.Windows.Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => ((MainWindow)System.Windows.Application.Current.MainWindow).answerCall.Visibility = Visibility.Visible));
}
foreach (XElement callVariables in xmlroots.Descendants("CallVariables"))
{
foreach (XElement callVariable in xmlroots.Descendants("CallVariable"))
{
list = callVariable.Element("value").Value;
}
}
// state = second.Element("state").Value;
}
我不确定您真正想要什么,但这会将 id 和调用变量提取到对话框对象列表中。如果你想使用 ling-to-xml 你需要先解析一个 XDocument,然后遍历所需的后代。最后用另一个循环从调用变量中获取值。
别忘了,要关心最后的异常。
public class Dialog
{
public int id;
public List<CallVariable> callVariables = new List<CallVariable>();
public struct CallVariable
{
public string name;
public string value;
}
}
public List<Dialog> GetDialogsFromXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
List<Dialog> dialogs = new List<Dialog>();
foreach (XElement item in doc.Root.Descendants("{http://jabber.org/protocol/pubsub}Dialog"))
{
int dialogid = int.Parse(item.Element("{http://jabber.org/protocol/pubsub}id").Value);
List<Dialog.CallVariable> callvariables = new List<Dialog.CallVariable>();
foreach (XElement callVariableNode in item.Descendants("{http://jabber.org/protocol/pubsub}callvariables").FirstOrDefault().Descendants("{http://jabber.org/protocol/pubsub}CallVariable"))
{
callvariables.Add(new Dialog.CallVariable() { name=callVariableNode.Element("{http://jabber.org/protocol/pubsub}name").Value, value = callVariableNode.Element("{http://jabber.org/protocol/pubsub}value").Value });
}
dialogs.Add(new Dialog() { id = dialogid, callVariables = callvariables });
}
return dialogs;
}
catch (Exception e)
{
//handle if something goes wrong
return null;
}
}
使用xml linq。您还需要使用命名空间来获取元素。您可以像我为对话框所做的那样通过获取 LocalName 来避免命名空间。 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement dialogs = doc.Descendants().Where(x => x.Name.LocalName == "dialogs").FirstOrDefault();
XNamespace ns = dialogs.GetDefaultNamespace();
var results = dialogs.Elements(ns + "Dialog").Select(x => new {
id = (int)x.Element(ns + "id"),
associatedDialogUri = (string)x.Element(ns + "associatedDialogUri"),
fromAddress = (string)x.Element(ns + "fromAddress"),
dnis = (int)x.Descendants(ns + "DNIS").FirstOrDefault(),
callType = (string)x.Descendants(ns + "callType").FirstOrDefault(),
dialedNumber = (int)x.Descendants(ns + "dialedNumber").FirstOrDefault(),
outboundClassification = (string)x.Descendants(ns + "outboundClassification").FirstOrDefault(),
callVariables = x.Descendants(ns + "CallVariable").Select(y => new {
name = (string)y.Element(ns + "name"),
value = (string)y.Element(ns + "value")
}).ToList(),
participants = x.Descendants(ns + "Participant").Select(y => new
{
actions = y.Descendants(ns + "action").Select(z => (string)z).ToList(),
namemediaAddress = (int)y.Element(ns + "mediaAddress"),
mediaAddressType = (string)y.Element(ns + "mediaAddressType"),
startTime = (DateTime)y.Element(ns + "startTime"),
state = (string)y.Element(ns + "state"),
stateCause = (string)y.Element(ns + "stateCause"),
stateChangeTime = (DateTime)y.Element(ns + "stateChangeTime")
}).ToList(),
state = (string)x.Descendants(ns + "state").FirstOrDefault(),
toAddress = (int)x.Descendants(ns + "toAddress").FirstOrDefault(),
uri = (string)x.Descendants(ns + "uri").FirstOrDefault()
}).ToList();
}
}
}
第一个问题是您只是调用 Descendants("Dialog")
、Descendants("CallVariables")
等。它们在全局命名空间中查找元素 - 但您要查找的所有元素都是 实际上 在 http://jabber.org/protocol/pubsub
的命名空间中,因为:
<notification xmlns="http://jabber.org/protocol/pubsub">
当您看到 xmlns="..."
时,它为所有后代设置了默认命名空间。该默认值可以被指定命名空间的元素名称显式覆盖 - 或者它可以被另一个具有 xmlns=...
的后代更改。 (您的文档包含多级默认值。)
幸运的是,由于从 string
到 XNamespace
的隐式转换以及 XName +(XNamespace, string)
运算符,LINQ to XML 使得指定命名空间变得容易:
XDocument doc = XDocument.Parse(...);
XNamespace pubsub = "http://jabber.org/protocol/pubsub";
// Find all the descendants with a local name of "Dialog" in the
// namespace specified by the pubsub variable
foreach (XElement dialog in doc.Descendants(pubsub + "Dialog"))
{
...
}
作为第二个问题,请看第二个循环:
foreach (XElement callVariables in xmlroots.Descendants("CallVariables"))
{
foreach (XElement callVariable in xmlroots.Descendants("CallVariable"))
{
list = callVariable.Element("value").Value;
}
}
这里存在三个问题:
- 您的文档中没有名为
CallVariables
的元素 - 取而代之的是 callvariables
。 XML 区分大小写。
我确定您不希望 every 调用变量在 every 调用变量元素中的组合.相反,我希望是这样的:
foreach (var callVariables in doc.Descendants(pubsub + "callvariables"))
{
// Note use of Elements, not Descendants. You still need
// the namespace part though...
foreach (var callVariable in callVariables.Elements(pubsub + "CallVariable"))
{
// Do what you want
}
}
目前您只是替换了循环体中的 list
变量,这意味着只有最后一次循环迭代才是真正有用的。
代码可能还有许多其他问题 - 解析 XML 然后检查 string 表示是否包含特定字符串似乎很奇怪(而不是检查特定元素的存在,例如)但这些应该让你开始。
我是 XML 使用 C# 的新手,我有一个 XML 我需要通过父级中的特定子级 我需要获取 id 和调用变量 variables 我这样做了但每次都没有经过循环
我是否需要遍历 xml 的所有父级,直到得到我想要的树??
xml
<message xmlns="jabber:client" to="1072@finesse1.dcloud.cisco.com" id="/finesse/api/User/1072/Dialogs__1072@finesse1.dcloud.cisco.com__104Y2" from="pubsub.finesse1.dcloud.cisco.com">
<event xmlns="http://jabber.org/protocol/pubsub#event">
<items node="/finesse/api/User/1072/Dialogs">
<item id="460c2d27-c914-4c24-a95f-edf9f8df45c21535">
<notification xmlns="http://jabber.org/protocol/pubsub">
<Update>
<data>
<dialogs>
<Dialog>
<associatedDialogUri></associatedDialogUri>
<fromAddress>1071</fromAddress>
<id>18639330</id>
<mediaProperties>
<DNIS>1072</DNIS>
<callType>AGENT_INSIDE</callType>
<dialedNumber>1072</dialedNumber>
<outboundClassification></outboundClassification>
<callvariables>
<CallVariable>
<name>callVariable1</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable2</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable3</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable4</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable5</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable6</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable7</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable8</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable9</name>
<value></value>
</CallVariable>
<CallVariable>
<name>callVariable10</name>
<value></value>
</CallVariable>
</callvariables>
</mediaProperties>
<mediaType>Voice</mediaType>
<participants>
<Participant>
<actions>
<action>ANSWER</action>
</actions>
<mediaAddress>1072</mediaAddress>
<mediaAddressType>AGENT_DEVICE</mediaAddressType>
<startTime>2017-09-15T19:23:36.872Z</startTime>
<state>ALERTING</state>
<stateCause></stateCause>
<stateChangeTime>2017-09-15T19:23:36.872Z</stateChangeTime>
</Participant>
<Participant>
<actions>
<action>UPDATE_CALL_DATA</action>
<action>DROP</action>
</actions>
<mediaAddress>1071</mediaAddress>
<mediaAddressType>AGENT_DEVICE</mediaAddressType>
<startTime>2017-09-15T19:23:36.609Z</startTime>
<state>INITIATED</state>
<stateCause></stateCause>
<stateChangeTime>2017-09-15T19:23:36.819Z</stateChangeTime>
</Participant>
</participants>
<state>ALERTING</state>
<toAddress>1072</toAddress>
<uri>/finesse/api/Dialog/18639330</uri>
</Dialog>
</dialogs>
</data>
<event>POST</event>
<requestId></requestId>
<source>/finesse/api/User/1072/Dialogs</source>
</Update>
</notification>
</item>
</items>
</event>
</message>
那就是 代码
XElement xmlroots = XElement.Parse(parsingNewXML);
//Dialog = xmlroots.Element("Dialog").Value;
var CallVariable = parsingNewXML.Contains("CallVariable");
var startCall = parsingNewXML.Contains("ALERTING");
if (CallVariable == true && startCall == true)
{
foreach (XElement callID in xmlroots.Descendants("Dialog"))
{
DialogID = callID.Element("id").Value;
//System.Windows.MessageBox.Show(DialogID);
System.Windows.Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => ((MainWindow)System.Windows.Application.Current.MainWindow).answerCall.Visibility = Visibility.Visible));
}
foreach (XElement callVariables in xmlroots.Descendants("CallVariables"))
{
foreach (XElement callVariable in xmlroots.Descendants("CallVariable"))
{
list = callVariable.Element("value").Value;
}
}
// state = second.Element("state").Value;
}
我不确定您真正想要什么,但这会将 id 和调用变量提取到对话框对象列表中。如果你想使用 ling-to-xml 你需要先解析一个 XDocument,然后遍历所需的后代。最后用另一个循环从调用变量中获取值。
别忘了,要关心最后的异常。
public class Dialog
{
public int id;
public List<CallVariable> callVariables = new List<CallVariable>();
public struct CallVariable
{
public string name;
public string value;
}
}
public List<Dialog> GetDialogsFromXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
List<Dialog> dialogs = new List<Dialog>();
foreach (XElement item in doc.Root.Descendants("{http://jabber.org/protocol/pubsub}Dialog"))
{
int dialogid = int.Parse(item.Element("{http://jabber.org/protocol/pubsub}id").Value);
List<Dialog.CallVariable> callvariables = new List<Dialog.CallVariable>();
foreach (XElement callVariableNode in item.Descendants("{http://jabber.org/protocol/pubsub}callvariables").FirstOrDefault().Descendants("{http://jabber.org/protocol/pubsub}CallVariable"))
{
callvariables.Add(new Dialog.CallVariable() { name=callVariableNode.Element("{http://jabber.org/protocol/pubsub}name").Value, value = callVariableNode.Element("{http://jabber.org/protocol/pubsub}value").Value });
}
dialogs.Add(new Dialog() { id = dialogid, callVariables = callvariables });
}
return dialogs;
}
catch (Exception e)
{
//handle if something goes wrong
return null;
}
}
使用xml linq。您还需要使用命名空间来获取元素。您可以像我为对话框所做的那样通过获取 LocalName 来避免命名空间。 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement dialogs = doc.Descendants().Where(x => x.Name.LocalName == "dialogs").FirstOrDefault();
XNamespace ns = dialogs.GetDefaultNamespace();
var results = dialogs.Elements(ns + "Dialog").Select(x => new {
id = (int)x.Element(ns + "id"),
associatedDialogUri = (string)x.Element(ns + "associatedDialogUri"),
fromAddress = (string)x.Element(ns + "fromAddress"),
dnis = (int)x.Descendants(ns + "DNIS").FirstOrDefault(),
callType = (string)x.Descendants(ns + "callType").FirstOrDefault(),
dialedNumber = (int)x.Descendants(ns + "dialedNumber").FirstOrDefault(),
outboundClassification = (string)x.Descendants(ns + "outboundClassification").FirstOrDefault(),
callVariables = x.Descendants(ns + "CallVariable").Select(y => new {
name = (string)y.Element(ns + "name"),
value = (string)y.Element(ns + "value")
}).ToList(),
participants = x.Descendants(ns + "Participant").Select(y => new
{
actions = y.Descendants(ns + "action").Select(z => (string)z).ToList(),
namemediaAddress = (int)y.Element(ns + "mediaAddress"),
mediaAddressType = (string)y.Element(ns + "mediaAddressType"),
startTime = (DateTime)y.Element(ns + "startTime"),
state = (string)y.Element(ns + "state"),
stateCause = (string)y.Element(ns + "stateCause"),
stateChangeTime = (DateTime)y.Element(ns + "stateChangeTime")
}).ToList(),
state = (string)x.Descendants(ns + "state").FirstOrDefault(),
toAddress = (int)x.Descendants(ns + "toAddress").FirstOrDefault(),
uri = (string)x.Descendants(ns + "uri").FirstOrDefault()
}).ToList();
}
}
}
第一个问题是您只是调用 Descendants("Dialog")
、Descendants("CallVariables")
等。它们在全局命名空间中查找元素 - 但您要查找的所有元素都是 实际上 在 http://jabber.org/protocol/pubsub
的命名空间中,因为:
<notification xmlns="http://jabber.org/protocol/pubsub">
当您看到 xmlns="..."
时,它为所有后代设置了默认命名空间。该默认值可以被指定命名空间的元素名称显式覆盖 - 或者它可以被另一个具有 xmlns=...
的后代更改。 (您的文档包含多级默认值。)
幸运的是,由于从 string
到 XNamespace
的隐式转换以及 XName +(XNamespace, string)
运算符,LINQ to XML 使得指定命名空间变得容易:
XDocument doc = XDocument.Parse(...);
XNamespace pubsub = "http://jabber.org/protocol/pubsub";
// Find all the descendants with a local name of "Dialog" in the
// namespace specified by the pubsub variable
foreach (XElement dialog in doc.Descendants(pubsub + "Dialog"))
{
...
}
作为第二个问题,请看第二个循环:
foreach (XElement callVariables in xmlroots.Descendants("CallVariables"))
{
foreach (XElement callVariable in xmlroots.Descendants("CallVariable"))
{
list = callVariable.Element("value").Value;
}
}
这里存在三个问题:
- 您的文档中没有名为
CallVariables
的元素 - 取而代之的是callvariables
。 XML 区分大小写。 我确定您不希望 every 调用变量在 every 调用变量元素中的组合.相反,我希望是这样的:
foreach (var callVariables in doc.Descendants(pubsub + "callvariables")) { // Note use of Elements, not Descendants. You still need // the namespace part though... foreach (var callVariable in callVariables.Elements(pubsub + "CallVariable")) { // Do what you want } }
目前您只是替换了循环体中的
list
变量,这意味着只有最后一次循环迭代才是真正有用的。
代码可能还有许多其他问题 - 解析 XML 然后检查 string 表示是否包含特定字符串似乎很奇怪(而不是检查特定元素的存在,例如)但这些应该让你开始。