public string xml(string sXmlMsg)
{
XmlDocument xmlDocument = new XmlDocument();
string sSqlString = "";
if (sXmlMsg.Length > 0)
{
StringReader stringReader = new StringReader(sXmlMsg);
xmlDocument.Load(stringReader);
XmlNamespaceManager m = new XmlNamespaceManager(xmlDocument.NameTable);
m.AddNamespace("ns", "urn:hl7-org:v3");
m.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
m.AddNamespace("schemaLocation", "urn:hl7-org:v3 ../multicacheschemas/POOR_IN200901UV.xsd");
XmlNode xmlNode = xmlDocument.SelectSingleNode("ns:POOR_IN200901UV/ns:controlActProcess/ns:subject/ns:observationRequest/ns:componentOf1/ns:encounter/ns:subject/ns:patient/ns:id", m);
XmlNode xmlNode2 = xmlNode.ChildNodes.Item(1);
foreach (XmlNode xmlNode1 in xmlNode.ChildNodes)
{
sSqlString = sSqlString + xmlNode1.Name + ",";
}
return sSqlString + xmlNode2.Attributes["extension"].InnerText;
}
return "解析失败";
}
注意事项:
1、创建一个字符流对象,读取xml字符串信息;创建一个XML文档对象,从字符流对象中加载
StringReader stringReader = new StringReader(sXmlMsg);
XmlDocument xmlDocument = xmlDocument.Load(stringReader);
2、如果命名空间的XML需要先创建命名空间对象,创建空间名
XmlNamespaceManager m = new XmlNamespaceManager(xmlDocument.NameTable);
m.AddNamespace("ns", "urn:hl7-org:v3");
m.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
m.AddNamespace("schemaLocation", "urn:hl7-org:v3 ../multicacheschemas/POOR_IN200901UV.xsd");
3、创建节点对象,获取节点,有命名空间的需要在节点前加空间名
XmlNode xmlNode = xmlDocument.SelectSingleNode("ns:POOR_IN200901UV/ns:controlActProcess/ns:subject/ns:observationRequest/ns:componentOf1/ns:encounter/ns:subject/ns:patient/ns:id", m);
4、子节点中有多个同名节点时可用Item(1)方法获取第几个节点的值
XmlNode xmlNode2 = xmlNode.ChildNodes.Item(1);
5、获取属性的值时用Attributes["extension"],注意这里是中括号“[]”,不是小括号“()”
xmlNode2 .Attributes["extension"] .InnerText;