简体   繁体   English

如何从C#中的xml中获取电话号码

[英]how to fetch phone number from xml in c#

I am having following xml response 我有以下xml响应

   <participantpasscode>92793519</participantpasscode>
    <dialInNumber>
        <phoneType>FREE</phoneType>
        <formattedNumber>0808 1005145</formattedNumber>
        <displayName>United Kingdom Freefone: 0808 1005145</displayName>
        <rawNumber>08081005145</rawNumber>
        <country>GBR</country>
    </dialInNumber>
    <dialInNumber>
        <phoneType>NATR</phoneType>
        <formattedNumber>0844 5610081</formattedNumber>
        <displayName>United Kingdom Primary: 0844 5610081</displayName>
        <rawNumber>08445610081</rawNumber>
        <country>GBR</country>
    </dialInNumber>
    <createDate>2014-11-19T15:09:09.815Z</createDate>

on phone type I can find this dial in number is toll number or toll free number for eg if phone type is 'Free' then it is toll free number otherwise this is toll numbet. 在电话类型上,我可以找到此拨入号码是收费电话号码或免费电话号码,例如,如果电话类型为“免费”,则为免费电话号码,否则为收费电话号码。 I want to write code in c# to fetch toll no and toll free no from this xml response. 我想用C#编写代码以从此xml响应中获取免费电话和免费电话。

Firstly you will have to add a root element to your xml otherwise this solution may not work. 首先,您必须在XML中添加根元素,否则此解决方案可能无法正常工作。 If you really can't add it you can get around it by using an XMLText reader and setting the conformance level to fragment. 如果您真的不能添加它,则可以使用XMLText阅读器并将一致性级别设置为fragment来解决它。

var doc = new XmlDocument();
doc.LoadXml(xml);
var children = doc["root"].ChildNodes;
foreach (XmlNode c in children)
{
    if (c.Name == "dialInNumber")
    {
        var type = c["phoneType"].InnerText;
        var number = c["rawNumber"].InnerText;
        //Do stuff with type and number
    }
}

Note that I've added a root element called root that's why on the third line I go into that element, other wise the doc.LoadXml method will throw an exception. 请注意,我添加了一个称为root的根元素,这就是为什么在第三行中我进入该元素的原因,否则doc.LoadXml方法将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM