我在XML
变量中跟随string __MessageIn
格式化字符串:
string _MessageIn=
<?Label TSRAY|RESERVATION|317859|SUCCESS?>
<Reservation xmlns="reservation.fidelio.2.0" mfShareAction="NA" mfReservationAction="EDIT">
<HotelReference>
<hotelCode>TSRAY</hotelCode>
</HotelReference>
<confirmationID>Y6Z7TFJDK</confirmationID>
<reservationID>347557</reservationID>
<reservationOriginatorCode>JA</reservationOriginatorCode>
<originalBookingDate>2010-08-16T22:53:23.000</originalBookingDate>
<StayDateRange timeUnitType="DAY">
<startTime>2010-08-19T00:00:00.000</startTime>
<numberOfTimeUnits>3</numberOfTimeUnits>
</StayDateRange>
<GuestCounts>
<GuestCount>
<ageQualifyingCode>ADULT</ageQualifyingCode>
<mfCount>2</mfCount>
</GuestCount>
<GuestCount>
<ageQualifyingCode>CHILD</ageQualifyingCode>
<mfCount>0</mfCount>
</GuestCount>
</GuestCounts>
...................
..................
</Reservation>
我试图从<hotelCode>TSRAY</hotelCode>
获取酒店代码的值,即 TSRAY ,但代码始终在NULL
中返回HotelReference
。
我尝试了以下代码行:
// query the XML document
XDocument doc = XDocument.Parse(_MessageIn);
var HotelReference = doc.Descendants("HotelReference").Select(x => new { HotelCode = x.Element("hotelCode").Value}).FirstOrDefault();
如何从XML
格式string variable
上方获取所需的值?
提前致谢!
答案 0 :(得分:2)
这是因为命名空间是xml的一部分。
有两种方法可以解决这个问题,要么删除名称空间“reservation.fidelio.2.0”,那么您的代码将无问题地运行。但这可能不太可行。
因此,在执行搜索时,我们必须将命名空间与节点名称一起传递。尝试以下操作,这将解决您的问题。希望这会有所帮助。
string ns = "reservation.fidelio.2.0";
string node = "HotelReference";
string elem = "hotelCode";
XName xn = XName.Get(node, ns);
XName xe = XName.Get(elem, ns);
var HotelReference = doc.Root.Descendants(xn).Select(x => new { HotelCode = x.Element(xe).Value }).FirstOrDefault();
答案 1 :(得分:0)
试试这个,
string _MessageIn="<?Label TSRAY|RESERVATION|317859|SUCCESS?> <Reservation xmlns='reservation.fidelio.2.0' mfShareAction='NA' mfReservationAction='EDIT'> <HotelReference> <hotelCode>TSRAY</hotelCode> </HotelReference> <confirmationID>Y6Z7TFJDK</confirmationID> <reservationID>347557</reservationID> <reservationOriginatorCode>JA</reservationOriginatorCode> <originalBookingDate>2010-08-16T22:53:23.000</originalBookingDate> <StayDateRange timeUnitType='DAY'> <startTime>2010-08-19T00:00:00.000</startTime> <numberOfTimeUnits>3</numberOfTimeUnits> </StayDateRange> <GuestCounts> <GuestCount> <ageQualifyingCode>ADULT</ageQualifyingCode> <mfCount>2</mfCount> </GuestCount> <GuestCount> <ageQualifyingCode>CHILD</ageQualifyingCode> <mfCount>0</mfCount> </GuestCount> </GuestCounts> ................... .................. </Reservation>";
string HotelCode = ""; // you can create HotelCode-Array to store all Hotelcodes
XmlDocument doc = new XmlDocument();
doc.LoadXml(_MessageIn);
XmlNodeList list=doc.GetElementsByTagName("hotelCode");
foreach (XmlNode node in list)
{
if (node.Name == "hotelCode")
{
HotelCode=node.InnerText;
}
}