Pages

Search

Friday, February 20, 2009

How to create entity in an Xml file .NET?

Please refer
Entity in Prog.Findings

.NET frame work has provided classes and methods which can be used to create entities in an xml file. I mean to create or delete or update an entity.

Below function is to delete an entity that exists in an xml file.

public void DeleteEntity(string strEntityName,bool blnChkForDependants)
{
if (_xmlDocument != null)
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
if(blnChkForDependants)
{
TextReader tr = new StreamReader(FilePath);
if (tr.ReadToEnd().Contains("&" + strEntityName + ";"))
{
tr.Close();
throw new Exception("Sorry you cannot delete this entity, there exists dependants on this " + strEntityName + " entity in xml file");
}
tr.Close();
}
string _strExistingSubSet = _oldXmlDocumentType.InternalSubset;
string _strFromEntity = _strExistingSubSet.Substring(_strExistingSubSet.IndexOf(" int intEntityEndIndex = _strFromEntity.IndexOf(">");
string _strEntityString = _strFromEntity.Substring(0,intEntityEndIndex+1);
_strExistingSubSet = _strExistingSubSet.Replace(_strEntityString, String.Empty);
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _strExistingSubSet);
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
_xmlDocument.Save(FilePath);
}
}
Below function is to save an exisiting entity or create new entity in xml file
public void SaveEntity(string strEntityName,string strValue)
{
if (_xmlDocument != null)
{
XmlNode objEntityNode = _xmlDocument.DocumentType.Entities.GetNamedItem(strEntityName);
if (objEntityNode != null)
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
string _strExistingSubSet = _oldXmlDocumentType.InternalSubset;
string _strFromEntity = _strExistingSubSet.Substring(_strExistingSubSet.IndexOf(" int intEntityEndIndex = _strFromEntity.IndexOf(">");
string _strEntityString = _strFromEntity.Substring(0, intEntityEndIndex + 1);
_strExistingSubSet = _strExistingSubSet.Replace(_strEntityString,"").Trim();
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _strExistingSubSet);
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
}
else
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _oldXmlDocumentType.InternalSubset + "\n ");
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
}
_xmlDocument.Save(FilePath);
}

}

No comments:

Post a Comment